简体   繁体   中英

How is this reduce operation mutating my original array?

I want to reduce the items array so that it includes a single element for "apple" with an updated quantity. The code below returns the correct reduced array, but it also mutating the original items array and I don't understand why.

 const items = [ {name: "apples", qty: 1}, {name: "bananas", qty: 1}, {name: "apples", qty: 3} ]; const reducedItems = items.reduce(function(newArray, currentItem) { const indexForCurrentItem = newArray.findIndex( ({name}) => name === currentItem.name ); // if current item is not in newArray, add it // but if it is already in newArray, update its quantity property there indexForCurrentItem === -1? newArray.push(currentItem): newArray[indexForCurrentItem].qty += currentItem.qty; return newArray; }, []); console.log(reducedItems); console.log(items); // reducedItems is correct: [{name: "apples", qty: 4}, {name: "bananas", qty: 1}] // but items is now: // [ // {name: "apples", qty: 4}, // {name: "bananas", qty: 1}, // {name: "apples", qty: 1} // ]

You are adding objects from items into newArray when you call newArray.push(currentItem) . newArray will hold the same objects (with the same reference) as in items . When you later call newArray[indexForCurrentItem].qty += currentItem.qty you update the object that is present in both arrays.

A simple fix would be to add copies of objects to the new array.

newArray.push(Object.assign({}, currentItem))

With this change newArray will hold (shallow) copies of objects. If you change the copy the original in items will be unaffected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM