Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I concatenate these two arrays? [duplicate]

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?

like image 721
alex Avatar asked Dec 08 '16 08:12

alex


3 Answers

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);
like image 183
Jaromanda X Avatar answered Sep 30 '22 05:09

Jaromanda X


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];
like image 26
guest271314 Avatar answered Sep 30 '22 05:09

guest271314


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.

like image 37
Andre Avatar answered Sep 30 '22 07:09

Andre