Ask Your Question
4

How can I combine 2 arrays into 1 array in an Angular ngrx store?

asked 2021-04-19 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-05-16 03:00:00 +0000

lalupa gravatar image

To combine 2 arrays into 1 array in an Angular ngrx store, you can use the concat method. Here's an example code snippet:

import { createReducer, on } from '@ngrx/store';
import { addFirstArray, addSecondArray } from './actions';

export interface AppState {
  combinedArray: any[];
}

const initialState: AppState = {
  combinedArray: [],
};

export const appReducer = createReducer(
  initialState,
  on(addFirstArray, (state, { firstArray }) => ({
    ...state,
    combinedArray: state.combinedArray.concat(firstArray),
  })),
  on(addSecondArray, (state, { secondArray }) => ({
    ...state,
    combinedArray: state.combinedArray.concat(secondArray),
  })),
);

In this example, we define an AppState interface that contains a combinedArray property. We then define an initialState object that sets the value of combinedArray to an empty array.

We then define an appReducer function that uses the createReducer method from @ngrx/store to handle the addFirstArray and addSecondArray actions. When an addFirstArray action is dispatched, we use the concat method to combine the firstArray payload with the current value of combinedArray. Similarly, when an addSecondArray action is dispatched, we use the concat method to combine the secondArray payload with the current value of combinedArray.

By using the concat method, we ensure that we don't mutate the original arrays and instead create a new updated array that we assign to the combinedArray property of the state.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-04-19 11:00:00 +0000

Seen: 15 times

Last updated: May 16 '22