'does array.filter() creates a new array?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
as per document says The filter() method creates a new array with all elements that pass the test implemented by the provided function.
According to document below script should console Learning
console.log(Arr[0].name) // Learning
var Arr = [{name:'Learning'},{name:'Questing'}]
var Arr2 = Arr.filter(it=> true);
Arr2[0].name = 'Stack-Over-Flow';
console.log(Arr[0].name) // Stack-Over-Flow
Solution 1:[1]
Yes, .filter
creates a new array, but the new array is the only new structure that is created. The items inside the array remain unchanged.
With your code, after filtering, you have a new array which contains 2 items, where both of those items are references to the same objects that were in the original array. So, mutating one of the objects in the new array results in the objects in the old array being mutated, because they point to the same object in memory.
If you wanted to avoid this, you'd have to deep clone the array first, perhaps with
const Arr2 = Arr
.filter(it => true)
.map(obj => ({ ...obj }));
Solution 2:[2]
.filter
does create a new array, but the array of the filtered elements from the old array.
While the element from the old is object, so that new array still keep its reference. To avoid that, you could do a .map
to clone the element for the whole new reference
var Arr = [{name:'Learning'},{name:'Questing'}]
var Arr2 = Arr.filter(it=> true).map(el => ({...el}));
Arr2[0].name = 'Stack-Over-Flow';
console.log(Arr[0].name)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | CertainPerformance |
Solution 2 | hgb123 |