Skip to content Skip to sidebar Skip to footer

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 conca

Solution 1:

With ES6 you can use destructuring:

const array1 = ["Banana","Apple"];
const array2 = ["Pineapple", "Peach"];
const array3 = [...array1, ...array2];

Solution 2:

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.

Solution 3:

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").

Solution 4:

arr1.push(...arr2)

Array.prototype.push() - JavaScript | MDN

Post a Comment for "How To Concat Arrays Immutable Way Js"