合并数组中的重复项 [英] Merge duplicated items in array

查看:206
本文介绍了合并数组中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数组,我想合并重复的项。

I have array and I want to merge duplicated items.

var arr = [{
    'id': 1,
    'text': 'ab'
}, {
    'id': 1,
    'text': 'cd'
}, {
    'id': 2,
    'text': 'other'
}, {
    'id': 3,
    'text': 'afafas'
}, {
    'id': 4,
    'text': 'asfasfa'
}];

var work = arr.reduce(function(p, c) {
    var key = c.id;

    p[key].text.push(c.text);
});

console.log(work);

输出必须是这样的:

[{
    'id': 1,
    'text': ["[ab] [cd]"]
}, {
    'id': 2,
    'text': 'other'
}, {
    'id': 3,
    'text': 'afafas'
}, {
    'id': 4,
    'text': 'asfasfa'
}]

这是我尝试过的结果,但失败了:( https://jsfiddle.net/ 2m7kzkba /

Here is what I tried but result is fail: ( https://jsfiddle.net/2m7kzkba/

推荐答案

这里是使用两个嵌套迭代器的简单方法

Here is a plain approach using two nested iterators

我们将遍历数组,并通过每个项目的嵌套迭代来查看是否有重复的项目
。我们标记重复的项目,以后将其删除。

We would be iterating through the array and see if duplicate items are there by nested iterating per item. We mark duplicate items and would delete them later.

柱塞

arr.forEach(function(item, idx){   

  //Do not iterate if it is marked
  if (typeof item.marked !== 'undefined')
        return;

   //Now lets go throug it from the next element
   for (var i = idx + 1; i < arr.length; i++) {

     //Check if the id matches
     if (item.id === arr[i].id) {

        //Mark
        arr[i].marked = true;

        //If the text field is already an array just add the element        
        if (arr[idx].text.constructor === Array) {
            arr[idx].text.push('[' + arr[i].text + ']');   
         }
         else {  //Create an array if not
            arr[idx].text = new Array('[' + arr[idx].text + ']', '[' + arr[i].text + ']');
         }

      }      
   }

 });


//Delete marked items now
for (var i = arr.length - 1; i >= 0; i--) {
   if (typeof arr[i].marked !== 'undefined')
      arr.splice(i, 1);
 }

这篇关于合并数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆