0

How do I search this array of objects and return the totals of all the price attributes

  Data = [ {id:0,name:”lamp”,price: 5}
            {id:1, name:”bed”, price:10}
             {id:2,name: “shelf”, price 3}]

   ... It will need to return a total of 18
Jack
  • 955
  • 1
  • 9
  • 30
  • `Data.reduce((a, e) => a + e.price, 0)` should do it although surely this is a [dupe](https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array).... Please also show an attempt at solving the problem yourself in the future. Thank you. – ggorlen May 18 '20 at 02:34

3 Answers3

1

The Array has the method reduce that is very often used in cases like this one.

It takes as the first parameter a function which will be called for every element in the array and a second, but optional, argument that will be the initial value.

So, in your case, you could do something like this:

const sum = Data.reduce((accumulator, obj) => accumulator + obj.price, 0)

The first time it's called the value of accumulator is 0, the next times the value of the accumulator will be the return value of the previous call of the function```

so it will work as the following:

// first call
// accumulator = 0
// obj = {id:0,name:”lamp”,price: 5}
return accumulator + obj.price

// second call
// accumulator = 5
// obj = {id:1, name:”bed”, price:10}
return accumulator + obj.price

// third call
// accumulator = 15
// obj = {id:2,name: “shelf”, price 3}
return accumulator + obj.price

// now accumulator = 18
Mestre San
  • 1,806
  • 15
  • 24
0

Same way you would search any other array. I'm giving you the general code, because you haven't specified any language

sum = 0
for element in array:
    sum = sum + element['attr']
return sum
  • It is tagged [tag:javascript], and the question is a dupe regardless so it's probably best to be closed. – ggorlen May 18 '20 at 02:37
  • oh, didn't see that. but yeah, seemed like a question you can google, so I just gave him the pseudocode so he can work it out on his own if he wanted to – Sumuk Shashidhar May 18 '20 at 02:39
0

I hope it is the answer you search

var Data = [ {id:0,name:'lamp',price: 5},{id:1, name:'bed', price:10},{id:1, name:'shelf', price:3}];

var sum = 0;
for (var i=0; i<Data.length;i++){
  sum += Data[i].price;
  
}
console.log(sum);
umusi
  • 167
  • 7