如何合并数组中的重复条目

时间:2016-05-14 00:05:09

标签: javascript arrays

我的记录很少,我想将它们合并到一个数组中。以下是一些示例数据:

var data = [{
    name:'book1',
    category: "nurse",
    location: "US edition"
},
{
    name:'book2',
    category: "nurse",
    location: "US edition"
},
{
    name:'book3',
    category: "patient",
    location: "CAN edition"
}]

关于最终结果应该是什么的想法:

var data = [{
    [name:'book1',name:'book2'],
    category: "nurse",
    location: "US edition"
},
{
    name:'book3',
    category: "patient",
    location: "CAN edition"
}]

我尝试合并记录,但是我无法找到并合并名称。这是我到目前为止编写的代码:

 var data = [
    {
        name:'book1',
        category: "nurse",
        location: "US edition"
    },
    {
        name:'book2',
        category: "nurse",
        location: "US edition"
    },
    {
        name:'book3',
        category: "patient",
        location: "CAN edition"
    }
],
i = 0,
j = data.length - 1,
current;

for (;i < data.length; i++) {
    current = data[i];
    for (;j > i; j--) {
        if (current.asset === data[j].asset && current.location === data[j].location) {
            if (Array.isArray(current.data)) {
                current.data = current.data.concat([data[j].data]);
            } else {
                current.data = [].concat([data[j].data, current.data]);
            }
            data.splice(j, 1);
        }
    }
} 

console.log(data);

有人可以向我建议,我可以将数据合并到数组中吗?

1 个答案:

答案 0 :(得分:2)

Array.prototype.reduce()非常适合这些工作。

var data = [
{name:'book1',
    category: "nurse",
    location: "US edition"
},
{
  name:'book2',
    category: "nurse",
    location: "US edition"
},
{    name:'book3',
    category: "patient",
    location: "CAN edition"
}
],
 reduced = data.reduce((p,c) => {var f = p.find(e => e.category == c.category && e.location == c.location);
                                 !!f ? f.name.push(c.name)
                                     : p.push({name:[c.name], category: c.category, location: c.location});
                                 return p;},[]);

document.write("<pre>" + JSON.stringify(reduced,null,2) + "</pre>");