验证数组javascript angularjs是否有多个索引

validate if there are multiple index on array javascript angularjs

本文关键字:索引 是否 数组 javascript angularjs 验证      更新时间:2023-09-26

所以我有了这个数组

array = [
{id:1,value:1},
{id:2,value:1},
{id:1,value:2},
{id:1,value:3},
{id:2,value:2},
{id:1,value:4},
{id:2,value:3}
]

我想把它整理一下,输出如下

array = [
{id:1,value:4},
{id:2,value:3}
]

我想用javascript实现,还是angularjs有能力做到这一点?谢谢你。

大家好,请看这里http://jsbin.com/nozag/2/edit?html,js,output

var app = angular.module('app', []);
app.controller('firstCtrl', function($scope){
 $scope.array = [
{id:1,value:1},
{id:2,value:1},
{id:1,value:2},
{id:1,value:3},
{id:2,value:2},
{id:1,value:4},
{id:2,value:3}
];
  $scope.uniq = [];
  for (var i=$scope.array.length-1; i>0; i--)
    {
     var arr = $scope.array[i];
      var contains = false;
      angular.forEach($scope.uniq, function(u){
        if (u.id==arr.id) 
          {
            contains = true;
          }

      });
      if(!contains){
         $scope.uniq.push(arr);
      }

    }
});

假设您想要计算具有特定id的对象的数量,那么在Underscore.js中定义的countBy如何?

array = _.countBy(array, function(obj) { return obj.id; });

用Java脚本写一个group by函数

function groupBy( array , f )
{
  var groups = {};
  array.forEach( function( o )
  {
    var group = JSON.stringify( f(o) );
    groups[group] = groups[group] || [];
    groups[group].push( o );  
  });
  return Object.keys(groups).map( function( group )
  {
    return groups[group]; 
  })
}

,称其为

var result = groupBy(list, function(item)
{
  return [item.id];
});

,在你的情况下,它将返回数据,即结果的值将是

   [
    [
      Object { id=1, value=1},
      Object { id=1, value=2},
      Object { id=1, value=3}, 
      Object { id=1, value=4}
    ], 
    [
      Object { id=2, value=1},
      Object { id=2, value=2},
      Object { id=2, value=3}
    ]
  ]

现在写一个函数来对相同id的值求和

function getData(groupByCategory)
{
  var  finalData=[];
    for(var i=0;i< groupByCategory.length;i++)
    {
    var temp=0;
        for(var j=0;j<groupByCategory[i].length;j++)
        {
            temp+=parseInt(groupByCategory[i][j].value);
        }
        finalData.push({"category":groupByCategory[i][0].id, "value":temp})
    }
   console.log(finalData);//final data is your required results
}

,称其为getData(结果);工作的小提琴在这里

虽然函数看起来相当大。但它是有效的。我在想别的办法。