1

is map return new array or modify the existing array in java script? i have an example in these example map should not modify the current array(not working) but it should modified array (its working fine),

let x = [{ 'name': 'a', checked: false },
{ 'name': 'b', checked: true },
{ 'name': 'c', checked: false }];

changing x based on the y name

let y = [{ 'name': 'a', checked: true },
{ 'name': 'b', checked: true },]

map function

y.forEach(ele =>{
  boss= x.map(item =>{
    if(ele.name == item.name){
      item.checked = true;
    }
    return item;
  });
});

expected output

x = [{"name":"a","checked":false},{"name":"b","checked":true},{"name":"c","checked":false}]

and

boss = [{"name":"a","checked":true},{"name":"b","checked":true},{"name":"c","checked":false}] 

example sackblitz

4
  • it depends. but what is the real question? Commented Feb 13, 2019 at 9:04
  • 1
    Map function is returning new array Commented Feb 13, 2019 at 9:05
  • expected x value is different in sackblitz. x before and after should be same right? why it is modifying i dont understand Commented Feb 13, 2019 at 9:05
  • @Isaac correct, but it should not modified x values right is my code is wrong ? Commented Feb 13, 2019 at 9:12

1 Answer 1

1

You could map new objects by taking an empty object and assign the actual object and the wanted update property with a Map.

var array = [{ name: 'a', checked: false }, { name: 'b', checked: true }, { name: 'c', checked: false }],
    update = [{ name: 'a', checked: true }, { name: 'b', checked: true }],
    updateMap = new Map(update.map(({ name, checked }) => [name, { checked }])),
    updatedArray = array.map(o => Object.assign({}, o, updateMap.get(o.name)));

console.log(updatedArray);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

2 Comments

i dont understand line 3 and 4 in your code , can you give some info?
line 3: it builds a Map out of the given update array and takes name as key and an object with checked as property. line4: Object.assign takes an empty array as target, adds the given object and takes the value of the map, if exists. the result is a new object, without any reference to the old object (in this case).

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.