So, we have an array whose elements are objects

var obj = [ { model : 'a1', speed : 20, locate : "aa" }, { model : 'a2', speed : 30, locate : "bb" }, { model : 'a3', speed : 15, locate : "bc" }, { model : 'a4', speed : 35, locate : "cd" }, ]; 

Tell me, please, how can I get the sum of all the speed properties of each object, and there may be a random number of objects inside the array.

  • So get, darling, get! And what do you want from us? - user207618 9:16 pm
  • Give an example of your code. - edem
  • Dada, that's it, that need help. So far, I have just figured out how to do it by assigning variables to the elements of the array and then it’s trivial to sum up variables, but this is not good, gentlemen. I honestly googled 2 hours and could not get an answer myself. - tews
  • And how were you looking? I on the first link in Google found the answer. - user207618
  • Thank you for the link that can help me find the answer to my question. Unfortunately, I found only how to get the sum of the elements of the array and the elements of the object separately, and at the current stage of my knowledge of js, alas, I can not put everything in a pile on my own. If you can, share the link or set the direction. - tews

2 answers 2

This simple example glues the locate properties of all objects in your collection:

 var arr = [ { model: 'a1', speed: 20, locate: "aa" }, { model: 'a2', speed: 30, locate: "bb" }, { model: 'a3', speed: 15, locate: "bc" }, { model: 'a4', speed: 35, locate: "cd" } ]; document.body.innerText = arr.reduce(function(p,c){return p+c.locate;},''); 

Hopefully helps to budge and add up speed.

  • It would be possible and it would be more transparent to hint, then anyone would guess where the movement of the cerebral muscle? - user207618 10:08 pm
  • in its own response, the TS - brain rocking straight: sweat, pain and steroids) - Sergiks

with the help of Array.prototype it turned out! Thanks for the tips)

 var arr = [ { model : 'a1', speed : 20, locate : "aa" }, { model : 'a2', speed : 30, locate : "bb" }, { model : 'a3', speed : 15, locate : "bc" }, { model : 'a4', speed : 35, locate : "cd" }, ]; Array.prototype.sum = function (prop) { var total = 0 for ( var i = 0, _len = this.length; i < _len; i++ ) { total += this[i][prop] } return total } console.log(arr.sum("speed")); 

  • one
    Fine! Only expanding the base objects is bad. So, for the future. - user207618