My goal is to condense the items
array to only have one element for "apple" with an updated quantity value. The code snippet below successfully achieves this, but it unexpectedly alters the original items
array as well. I'm puzzled by this behavior and would appreciate some insight.
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
);
// Add the item if it doesn't exist in newArray yet
// If it does, update its quantity property
indexForCurrentItem === -1
? newArray.push(currentItem)
: newArray[indexForCurrentItem].qty += currentItem.qty;
return newArray;
}, []);
console.log(reducedItems);
console.log(items);
// The reducedItems array shows: [{name: "apples", qty: 4}, {name: "bananas", qty: 1}]
// However, the items array now looks like:
// [
// {name: "apples", qty: 4},
// {name: "bananas", qty: 1},
// {name: "apples", qty: 1}
// ]