如果我有一个对象数组

[
    {name: 'John', count: 5, isunique: false, occupation: 'carpenter'},
    {name: 'Bob', count: 6,  isunique: false, occupation: 'carpenter'},
    {name: "John", count: 9, isunique: false, occupation: "barber"}
]


(此数组很大),我想确定哪些职业是唯一的,并在这种情况下返回一个新的数组,其中仅更改布尔isunique,如下所示:

[
    {name: 'John', count: 5, isunique: false, occupation: 'carpenter'},
    {name: 'Bob', count: 6,  isunique: false, occupation: 'carpenter'},
    {name: "John", count: 9, isunique: true, occupation: "barber"}
]


这有可能在大型数组的Javascript中高效地完成吗?我在这里完全茫然。

最佳答案

一种选择是:

var count = data.reduce(function(ret, el) {
    ret[el.occupation] = (ret[el.occupation] || 0) + 1;
    return ret;
}, {});

data.forEach(function(el) { el.isunique = count[el.occupation] === 1; });

09-30 23:31