在javascript数组对象中对项目进行分组

时间:2016-06-28 14:30:26

标签: javascript arrays

我有一个javascript数组对象:

var items = [
               {address: 'abc'}, {address: 'abc'}, {address: 'abc'}, 
               {address: 'abc'}, {address: 'wer'}, {address: 'xyz'}, 
               {address: 'xyz'}, {address: 'xyz'}
            ];

我想要做的是我将2个项目视为一个项目..如果项目的地址重复两次..我认为它是一个项目...单个唯一项目将被视为一个...

我希望它的输出如下:

[
   {address: 'abc'}, {address: 'abc'}, 
   {address: 'wer'}, 
   {address: 'xyz'}, {address: 'xyz'}
];

以上是预期产量..

概念是这样的:

abc , abc , abc SHOULD BE abc, abc
xyz , xyz, xyz SHOULD BE xyz, xyz
wer SHOULD BE wer

到目前为止我所尝试的是:

var items = [
           {address: 'abc'}, {address: 'abc'}, {address: 'abc'}, 
           {address: 'abc'}, {address: 'wer'}, {address: 'xyz'}, 
           {address: 'xyz'}, {address: 'xyz'}
        ];
  var itemsNew = [];
  var preItem  = '';
  var a        = 1;
  var x        = false;

  for(var i = 0; i < items.length; i++){

    var itemDeliveryAddress = items[i].address;

    if(a == 2){

      if(preItem == itemDeliveryAddress){

        preItem = '';
        a=1;
      }
      else {

        preItem = '';
        a=1;
        itemsNew.push(itemDeliveryAddress);
      }
    }
    else {

      a++;
      preItem = itemDeliveryAddress;
      itemsNew.push(itemDeliveryAddress);    
    }
  }

但是上面的代码没有正确地对项目进行分组..我得到了这个输出:

abc,abc,wer,xyz,xyz

注意:我先按升序排序数组

2 个答案:

答案 0 :(得分:4)

您可以使用计数器和Array#filter过滤它。

  

filter() 方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

此提案使用thisArg,一个非常空的对象作为回调内的this对象。

基本上this[a.address]是计数器,如果不存在,则初始化为零,然后加1。

计数后,计数器用于返回。如果值为奇数,则该项目将包含在结果集中。

虽然this在所有回调中都是持久的,但不需要排序,因为计数器不需要特定的顺序。

&#13;
&#13;
var items = [{ address: 'abc' }, { address: 'abc' }, { address: 'abc' }, { address: 'abc' }, { address: 'wer' }, { address: 'xyz' }, { address: 'xyz' }, { address: 'xyz' }],
    result = items.filter(function (a) {
        this[a.address] = (this[a.address] || 0) + 1;
        return this[a.address] % 2;
    }, Object.create(null));

console.log(result);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用array.splice来修改数组。

&#13;
&#13;
//Initialize array (sorted)
var items = [{ address: 'abc' }, { address: 'abc' }, { address: 'abc' }, { address: 'abc' }, { address: 'wer' }, { address: 'xyz' }, { address: 'xyz' }, { address: 'xyz' }];
var groupedProperty = "address";   //Modify this string to change which property to group by
//Iterate through sorted array
for( var i = 1; i < items.length; i++ )  //Iterate, start with the 2nd (since we refer to `i - 1`) item
    if( items[i][groupedProperty] == items[i-1][groupedProperty] )  //Check if current item's prop matches previous item's prop
      items.splice(i, 1);                //Remove current item inplace, since there is a match. Other items (> i) shifted back automatically

console.log(items);
&#13;
&#13;
&#13;