通过合并具有相同字段值的元素,获得卑鄙数组的唯一元素

Get unique elements of an abject array by merging elements with same value of field

本文关键字:元素 唯一 数组 合并 字段      更新时间:2023-09-26

有一个包含一些对象的数组,这些对象可能具有相同标题(不同类型)的元素。应该合并这些元素以获得具有唯一标题的结果数组,但单个对象的信息不应该丢失。

所以这个。。。

array = [
    { id: 1, title: 'one', type: 'infos' },
    { id: 2, title: 'two', type: 'infos' },
    { id: 3, title: 'same', type: 'infos' },   // <--
    { id: 1, title: 'oneDiff', type: 'article' },
    { id: 2, title: 'same', type: 'article' },
    { id: 3, title: 'three', type: 'article' } // <--
]

应该得到:

distinct = [
    { id: 1, title: 'one', type: 'infos' },
    { id: 2, title: 'two', type: 'infos' },
    { id: 1, title: 'oneDiff', type: 'article' },
    { id: 3, title: 'three', type: 'article' },
    { id: [{ id: 3, type: 'infos'}, { id: 2, type: 'article'}], title: 'same', type: 'multiple' }
]

我试着从这个开始,但我没能得到我需要的结果:

var unique = {};
var distinct = [];
for( var i in array ){
    if( typeof(unique[array[i].title]) == "undefined"){
        distinct.push(array[i].title);
    }
    unique[array[i].title] = 0;
}

我试着用array.reduce来做。所以如果你不支持ie8,你可以使用它。有一点需要注意:如果没有额外的数组,我无法做到这一点。

var tempArray = [];
var result = array.reduce(function (memo, element) {
    var index = tempArray.indexOf(element.title);
    if (index === -1) {
        tempArray.push(element.title);
        memo.push(element);
    } else {
        if (typeof memo[index].id === 'number') {
            memo[index].id = [{
                id: memo[index].id,
                type: memo[index].type
            }];
            memo[index].type = 'multiple';
        }
        memo[index].id.push({
            id: element.id,
            type: element.type
        });
        tempArray.push(null);
    }
    return memo;
}, []);

jsbin 的示例

我有一个快速的想法。为什么不将标题和类型连接在一起,并将它们放在一个数组中呢?所以如果你有

title: 'apple'
type: 'golden'

然后你会把它们和下划线连在一起,得到

apple_golden

当然,只有在任何标题或类型中都没有下划线的情况下,这才有效。如果你这样做了,你可以制作一个独特的字符组合,象征着一个新词的开始。

例如:

apple!-!-!golden