通过比较ID& ID来增加数字将它推入新阵列

时间:2017-12-28 12:02:37

标签: javascript arrays angularjs json

我想添加具有相同seq id的所有数字,并将其与summation值一起推入名为final的新数组中,如下所示。

INPUT =>

$scope.initial = [{seq:11, name:'ABC', number:20},
                  {seq:11, name:'ABC', number:50},
                  {seq:11, name:'ABC', number:80},
                  {seq:12, name:'DEF', number:30},
                  {seq:13, name:'JKL', number:10},
                  {seq:13, name:'JKL', number:15}];

OUTPUT =>

$scope.final  = [{seq:11, name:'ABC', number:150},
                 {seq:12, name:'DEF', number:30},
                 {seq:13, name:'JKL', number:25}];

谢谢!

3 个答案:

答案 0 :(得分:0)

 $scope.final = [];
 var acc = {};

 for(const {seq, name, number} of $scope.initial){

   if(seq === acc.seq && name === acc.name){
     acc.number += number;
   }else{
     $scope.final.push(acc = {seq, name, number});
   }

 }

只需使用累加器来跟踪当前结果元素。然后检查当前迭代的元素是否与该累加器匹配,如果是这样总结,如果不是将当前元素添加为新的累加器。

答案 1 :(得分:0)

阵列循环&如果没有,请检查是否有seq然后添加此



var m = [{
    seq: 11,
    name: 'ABC',
    number: 20
  },
  {
    seq: 11,
    name: 'ABC',
    number: 50
  },
  {
    seq: 11,
    name: 'ABC',
    number: 80
  },
  {
    seq: 12,
    name: 'DEF',
    number: 30
  },
  {
    seq: 13,
    name: 'JKL',
    number: 10
  },
  {
    seq: 13,
    name: 'JKL',
    number: 15
  }
];
var grouped = [];
m.forEach(function(a) {
  if (!this[a.seq]) {
    this[a.seq] = {
      seq: a.seq,
      name: a.name,
      number: 0
    };
    grouped.push(this[a.seq]);
  }
  this[a.seq].number = (+this[a.seq].number + +a.number);
}, Object.create(null));

console.log(grouped);




答案 2 :(得分:0)

您可以使用reduce来完成您的任务:

$scope.initial = [
    {seq:11, name:'ABC', number:20},
    {seq:11, name:'ABC', number:50},
    {seq:11, name:'ABC', number:80},
    {seq:12, name:'DEF', number:30},
    {seq:13, name:'JKL', number:10},
    {seq:13, name:'JKL', number:15}
];

var objReduced = arr.reduce(function(acc, cur){
    acc[cur.seq] ? acc[cur.seq].number += cur.number : acc[cur.seq] = cur;
    return acc;
}, {});

$scope.final = Object.keys(objReduced).map(function(x){ return objReduced[x]; });