5

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

2
  • 1
    "Bonus" No. Ask one question per question, not two. If you have a second question, ask it separately (after having done thorough research, of course). Commented Dec 18, 2016 at 15:08
  • "How do I overwrite items with same id (immutable way)?" You don't. You create a new array with a different value in one of the slots. Commented Dec 18, 2016 at 15:08

3 Answers 3

15

With ES6 you can use destructuring:

const array1 = ["Banana","Apple"];
const array2 = ["Pineapple", "Peach"];
const array3 = [...array1, ...array2];
Sign up to request clarification or add additional context in comments.

2 Comments

this is better than the accepted answer for most modern use cases
This is not destructuring.
7

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.

1 Comment

Number and String are immutables in Javascript. developer.mozilla.org/en-US/docs/Glossary/Mutable
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.