does array.filter() creates a new array?

大憨熊 提交于 2021-02-17 05:17:20

问题


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

回答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 }));



回答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)


来源:https://stackoverflow.com/questions/63941282/does-array-filter-creates-a-new-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!