Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat arrays immutable way JS

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'}]

like image 986
alphiii Avatar asked Nov 29 '22 22:11

alphiii


2 Answers

With ES6 you can use destructuring:

const array1 = ["Banana","Apple"];
const array2 = ["Pineapple", "Peach"];
const array3 = [...array1, ...array2];
like image 159
Max Cruz Avatar answered Dec 01 '22 13:12

Max Cruz


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.

like image 37
SLaks Avatar answered Dec 01 '22 14:12

SLaks