7

This is the code (a Vuex mutation):

export const CREATE_PANORAMAS = (state, panoramas) => {
  console.log('building.panoramas:', state.building.panoramas)
  console.log('panoramas:', panoramas)
  state.building.panoramas.concat(panoramas)
  console.log('result:', state.building.panoramas)
} 

This the result with the respective logs:

[] // building.panoramas
[{ name: "", objectId: "5849133aac502e006c581b58" }] // panoramas
[] // result

Why aren't the two arrays concatenating?

alex
  • 7,111
  • 15
  • 50
  • 77

3 Answers3

17

From documentation - The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

One way to use concat would be to do the following

state.building.panoramas = state.building.panoramas.concat(panoramas)

Or you can simply

[].push.apply(state.building.panoramas, panoramas);
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
2

The issue is you do not assign the result of the concatenation to a the state.building.panoramas array as indicated by @JaromandaX.

You can also use rest element, spread element, destructuring assignment to concatenate two or more arrays

[...state.building.panoramas] = [...state.building.panoramas, ...panoramas];
guest271314
  • 1
  • 15
  • 104
  • 177
1

I think you need to assign state.building.panoramas.concat(panoramas) to something first, or you could directly put it on your 'result' line

sampleArray.concat(moreValues) returns the concatenated array, it doesn't concatenate 'moreValues' to sampleArray itself.

Andre
  • 54
  • 4