Reputation: 1645
I wonder how to contact array that is immutable. Lets imagine I start with array list = [4,1]
, and then I receive array from action response like so items = [5,2,6]
. How do I concant arrays that the result is [4,1,5,2,6]
and that operation is not mutable.
Bonus: How do I overwrite items with same id (immutable way)? Lets imagine this our array in store books=[{'id':1, 'title': 'Cool story'}, {'id':2, 'title': 'Bad story'}]
. Other array that needs to overwrite books (last sync from API) otherArray = [{'id':3, 'title': 'Super story'}, {'id':1, 'title': 'Very cool story'}]
. So result should be [{'id':2, 'title': 'Bad story'}], {'id':3, 'title': 'Super story'}, {'id':1, 'title': 'Very cool story'}]
Upvotes: 5
Views: 11338
Reputation: 1375
With ES6 you can use destructuring:
const array1 = ["Banana","Apple"];
const array2 = ["Pineapple", "Peach"];
const array3 = [...array1, ...array2];
Upvotes: 15
Reputation: 44386
Although as mentioned, the built-in method .concat()
will solve your problem, you might wish to look into the Lodash library. In particular, the bonus question could be solved with _.unionBy(otherArray, books, "id")
.
Upvotes: 1
Reputation: 887449
Javascript does not have immutable types.
It sounds like you're actually asking to concatenate arrays without mutating the existing instances.
As stated clearly in the documentation, the concat()
method does that.
Upvotes: 7