获取对象数组中所有指定元素的总和

时间:2017-04-26 08:17:02

标签: javascript arrays object multidimensional-array

我有一个对象数组作为folllows

[
    {"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}
]

我正在寻找一个函数来获取当前对象中所有'width'元素的总和。

类似的东西:

function getAllBefore(current) {
    // here i want to get the sum of the previous 4 'width' elements in the object
}
getAllBefore(obj[5]);

5 个答案:

答案 0 :(得分:5)

为更简单,更可重用的代码传递给方法的对象和索引,如下所示:

function getAllBefore(obj, index){
  var sum=0;
  for(var i=0; i<index; i++){
    sum+=obj[i].width;
  }

  return sum;
}

并称之为:

getAllBefore(obj, 5);

答案 1 :(得分:2)

这是一个使用切片首先返回具有正确长度的数组并使用reduce来返回总和的示例

const getSum = (objNum, arr) => {
  const newArr =  arr.slice(0, objNum - 1)
  return newArr.reduce((current, next) => {
    return current + next.width;
  }, 0)
}

和ES5

var getSum = (objNum, arr) => {
  vat newArr =  arr.slice(0, objNum - 1)
  return newArr.reduce(function(current, next) {
    return current + next.width;
  }, 0)
}

并在第1行

const getSum = (objNum, arr) => arr.slice(0, objNum - 1).reduce((current, next) =>  current + next.width, 0)

答案 2 :(得分:1)

让我们在JavaScript中使用reduce

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));

答案 3 :(得分:1)

如果您在不知道元素索引的情况下寻找解决方案,但只想发送对象,那么您需要检查当前项目的所有属性和可用项目,您可以这样做:

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]);

答案 4 :(得分:1)

function count(stack) {
    var totWidth = 0;
    stack.forEach(function(element) {
      totWidth = totWidth+element.width;
    });
  return totWidth;
}

工作example