Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.