数组中对象的总和值

时间:2016-02-18 11:54:50

标签: javascript arrays

我想创建一个包含多个对象的数组的总和。

这是一个例子:     var array = [{"adults":2,"children":3},{"adults":2,"children":1}];

如何将成人和儿童总数的总和归还给每个人的新变量?

谢谢, 角

8 个答案:

答案 0 :(得分:6)

  

使用Array.prototype.reduce(),reduce()方法对累加器和数组的每个值(从左到右)应用函数以将其减少为单个值。

试试这个:

var array = [{
  "adults": 2,
  "children": 3
}, {
  "adults": 2,
  "children": 1
}];

var val = array.reduce(function(previousValue, currentValue) {
  return {
    adults: previousValue.adults + currentValue.adults,
    children: previousValue.children + currentValue.children
  }
});
console.log(val);

答案 1 :(得分:5)

 array = [{"adults":2,"children":3},{"adults":2,"children":1}];

 var totalChild = this.array.reduce((accum,item) => accum + item.children, 0)

 console.log(totalChild) //output 4

答案 2 :(得分:1)

看到没有人发布此消息...这是一个不错的速记方法:

testarr = [["Z",33,34,35,36,"END"],["A",1,2,3,4,5,"B"],["C",8,9,10,"D"],["B",6,7,"C"],["G",27,28,29,30,31,32,"Z"],["D",11,12,13,14,"E"],["begin",-10,-5,0,"A"],["F",19,20,21,22,23,24,25,26,"G"],["E",15,16,17,18,"F"]]

def sortingAS(tararr):
    temparr = []
    for i in tararr:
        if not temparr:
            temparr.append(i)
            continue
        checker = True
        for j in temparr:
            if j[0]==i[-1]:
                j.pop(0)
                temparr.append(i+j)
                temparr.remove(j)
                checker = False
                break
            if j[-1]==i[0]:
                i.pop(0)
                temparr.append(j+i)
                temparr.remove(j)
                checker = False
                break
        if checker:
            temparr.append(i)
        #print(temparr)
    return temparr

def sortingMain(target):
    toreturn = sortingAS(target)
    if len(toreturn)>1:
        toreturn = sortingMain(toreturn)
    return toreturn

resforme = sortingMain(testarr)
print(resforme)

示例:

.reduce((acc, curr) => acc + curr.property, 0)

答案 3 :(得分:0)

var array = [{"adults":2,"children":3},{"adults":2,"children":1}];
var sumProps = prop => (sum, obj) => sum += obj[prop];
var adultsCount = array.reduce( sumProps('adults'));
var childrenCount = array.reduce( sumProps('children'));

答案 4 :(得分:0)

我们不是为您编写代码,但我想您应该尝试:

var val = array.reduce(function (sum, tuple) {
    return { adults: sum.adults + tuple.adults,
             children: sum.children + tuple.children };
});

答案 5 :(得分:0)

您可以为此任务编写一个函数,该函数使数组迭代一个属性,应该添加该值。

该函数的关键特性是Array#reduce方法和一个返回实际计数calue和实际属性值的属性。

function count(array, key) {
    return array.reduce(function (r, a) {
        return r + a[key];
    }, 0);
}

var array = [{ "adults": 2, "children": 3 }, { "adults": 2, "children": 2 }],
    adults = count(array, 'adults'),
    children = count(array, 'children');

document.write('Adults: ' + adults + '<br>');
document.write('Children: ' + children + '<br>');

答案 6 :(得分:0)

将每个要素的总和变为单独的变量:

var array = [{"adults":2,"children":3},{"adults":2,"children":1}];
var adults_sum = 0, children_sum = 0;

array.forEach(function(obj){
    adults_sum += obj["adults"];
    children_sum += obj["children"];
});

console.log(adults_sum, children_sum); // 4 4

答案 7 :(得分:-1)

也许可以帮助您,这也无需使用减少功能。

var sumAdult=0;
var sumChildren=0;
var array = [{
  "adult": 2,
  "children": 3
}, {
  "adult": 2,
  "children": 1
}];
 function x(a,b){
   return a+b;
 }
for (y in array){  
  sumAdult=x(0, array[y].adult);
  console.log( "adult :" + sumAdult);
  sumChildren=x(0, array[y].children);
  console.log( "children :" + sumChildren);
}