Here you need to understand a few things:
- map receives an array as input and returns a new array.
- if an element of the original array was an object, then it will be passed by reference (that is, item and arr [index] are the same object)
- The arrow function in the nonblock form returns the result of the last operation.
Miracles became possible because the basic features of the map and turnout functions were not taken into account. Well, it is clearly not an effective solution to iterate through the numbers array for each element of the arr array.
From the question it is not clear which one you want to get the result on; I will demonstrate 3 (more efficient) options:
- change selected to arr
- create newArr from arr array objects
- create newArr from copies of arr objects.
Go!
Change selected to arr :
var arr = [{name: 'Hello', number: 14}, {name: 'World', number: 18}, {name: '!', number: 31}]; var numbers = [14, 31]; arr.forEach(x => x.selected = numbers.indexOf(x.number) > -1); console.log(arr);
Create newArr from the arr array objects :
var arr = [{name: 'Hello', number: 14}, {name: 'World', number: 18}, {name: '!', number: 31}]; var numbers = [14, 31]; var newArr = arr.map(x => { x.selected = numbers.indexOf(x.number) > -1; return x; }); console.log(newArr); console.log(arr);
Create a newArr from copies of arr objects :
var arr = [{name: 'Hello', number: 14}, {name: 'World', number: 18}, {name: '!', number: 31}]; var numbers = [14, 31]; var newArr1 = arr.map(x => { var o = Object.assign({}, x); o.selected = numbers.indexOf(o.number) > -1; return o; }); var newArr2 = arr.map(x => Object.assign({selected: (numbers.indexOf(x.number) > -1)}, x)); var newArr3 = arr.map(x => { return { ...x , selected: (numbers.indexOf(x.number) > -1) }; }); console.log(newArr2); console.log(arr);