I have an array of objects as folllows
[
{\"width\":128.90663423245883,\"height\":160,\"X\":0,\"Y\":140},
{\"width\":277.0938568683375,\"height\":263,\"X
Let's use reduce in JavaScript
var arr = [
{"width":128.90663423245883,"height":160,"X":0,"Y":140},
{"width":277.0938568683375,"height":263,"X":128.90663423245883,"Y":37},
{"width":264.8267031014369,"height":261,"X":277.0938568683375,"Y":39},
{"width":229.14003389179788,"height":60,"X":264.8267031014369,"Y":240},
{"width":10.032771905968888,"height":177,"X":229.14003389179788,"Y":123}
];
console.log(arr.reduce((acc, b) => acc + b.width, 0.0));
Here is an example using a slice to first return the array with the correct length and the a reduce to return the sum
const getSum = (objNum, arr) => {
const newArr = arr.slice(0, objNum - 1)
return newArr.reduce((current, next) => {
return current + next.width;
}, 0)
}
and in ES5
var getSum = (objNum, arr) => {
vat newArr = arr.slice(0, objNum - 1)
return newArr.reduce(function(current, next) {
return current + next.width;
}, 0)
}
and in 1 line
const getSum = (objNum, arr) => arr.slice(0, objNum - 1).reduce((current, next) => current + next.width, 0)
For an easier and more reusable code pass to the method the object and the index, as follows:
function getAllBefore(obj, index){
var sum=0;
for(var i=0; i<index; i++){
sum+=obj[i].width;
}
return sum;
}
And call it like this:
getAllBefore(obj, 5);
function count(stack) {
var totWidth = 0;
stack.forEach(function(element) {
totWidth = totWidth+element.width;
});
return totWidth;
}
working example
If you are looking for solution without knowing index of element but you want only to send object, then you will need to check all properties of current item with available items and you can do it like this:
var items = [
{"width":128.90663423245883,"height":160,"X":0,"Y":140},
{"width":277.0938568683375,"height":263,"X":128.90663423245883,"Y":37},
{"width":264.8267031014369,"height":261,"X":277.0938568683375,"Y":39},
{"width":229.14003389179788,"height":60,"X":264.8267031014369,"Y":240},
{"width":10.032771905968888,"height":177,"X":229.14003389179788,"Y":123}
];
function getAllBefore(current) {
var sum = 0;
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (current.width == item.width && current.height == item.height && current.X == item.X && current.Y == item.Y)
{
return sum;
}
sum += item.width;
}
}
getAllBefore(items[2]);