var arr = [
{item : banana_3, price : 100},
{item : banana_2, price : 200},
{item : apple, price : 500}];
var arr2 = [
{item : banana, price : 300},
{item : apple, price : 500}];
I tried
for(let i = 0; i<arr.length; i++){
if(arr[i].item.includes('banana')){
arr[i].price = arr[i+1].price ///???
}
}
I’d like to make arr2 from arr1, remove banana2 and banana3 elements within the array, and add up the price. How can I do that?
4
Answers
You can use
Array.prototype.reduce
to group items based on a common prefix before the underscore:You can use a simple regex to extract the first part of the item name (which I call the ‘key’), which would not include the underscore or anything after it. Then, you can use reduce to build up an object for each of those keys, incrementing the price of the matching object each time. Finally, use Object.values to return just the array of objects.
You could get all items and reduce with an object.
You can avoid an intermediate array with mapping items with new names in a separate object and collect new items in an array: