Merge two arrays

How can I merge two arrays with data coming from the store and have the merged array still updating whenever something is added to the store.

This doesn’t work:

arrayOne.toArray().concat(arrayTwo.toArray())

It creates a merged array but of course no elements are added when the store is updated

Fyi: both arrays return an array of models from a different endpoint.

Try Ember.computed.union.

array1: ...,
array2: ...,
merged: Ember.computed.union('array1', 'array2')

Example: http://emberjs.jsbin.com/zodeh/2/edit?html,js,output

2 Likes

Looks great! Two quick questions

  • performance: does it only recompute when an element is added to one of the arrays or also when a property of an object in the array has changed. I prefer the first one with less computations
  • can this also be done when the two arrays are not in a property? I use and rsvp hash to retrieve the data and then want to return the merged array as the model for a route.

I just tried this and it seems to be computationally heavy. Every time a property of one of the object changes it recalculates.

you can just do this;

let marged_array = [arrayOne, arrayTwo].reduce((first, last)=>{
return first.addObjects(last);
},[]);