我知道有很多方法可以过滤数组中的唯一值,但是对于给定字段具有唯一值的对象的过滤数组呢?
例如,我有[obj1, obj2, obj3, ...]
,其中每个对象的格式如下:
{
firstName: "...",
lastName: "..."
}
如何过滤数组以最终数组为止所有对象都有唯一的名字?单行会更好,但不会以可读性为代价。
答案 0 :(得分:6)
仅过滤那些先前未在数组中找到的项目。我们将cond
定义为返回是否应该考虑两个项目"相等"。
function uniqueBy(a, cond) {
return a.filter((e, i) => a.findIndex(e2 => cond(e, e2)) === i);
}
const test = [
{ firstname: "John", lastname: "Doe" },
{ firstname: "Jane", lastname: "Doe" },
{ firstname: "John", lastname: "Smith" }
];
console.log(uniqueBy(test, (o1, o2) => o1.firstname === o2.firstname));

答案 1 :(得分:2)
您可以将数组缩减为Map,然后将地图值传播回数组。
如果您想要保持遇到第一个对象,您必须检查地图是否已将firstName
作为关键字,并且只有在它尚不存在时才设置。
const arr = [{"firstname":"Robert","lastname":"Smith"},{"firstname":"Francis","lastname":"Collins"},{"firstname":"Robert","lastname":"Ludlum"},{"firstname":"Francis","lastname":"bacon"}];
const result = [...arr.reduce((map, obj) => map.has(obj.firstname) ? map : map.set(obj.firstname, obj), new Map()).values()];
console.log(result);

如果您想保留最后一个对象,可以跳过检查,只需设置它们:
const arr = [{"firstname":"Robert","lastname":"Smith"},{"firstname":"Francis","lastname":"Collins"},{"firstname":"Robert","lastname":"Ludlum"},{"firstname":"Francis","lastname":"bacon"}];
const result = [...arr.reduce((map, obj) => map.set(obj.firstname, obj), new Map()).values()];
console.log(result);

答案 2 :(得分:1)
您可以使用reduce方法,并将初始值设置为数组,有条件地将对象推送到新数组,即如果第一个名称尚不存在:
var arr = [ { firstname: "John",
lastname: "Doe" },
{ firstname: "Jane",
lastname: "Doe" },
{ firstname: "John",
lastname: "Doe" }];
console.log(
arr.reduce(
function(unique_arr, obj) {
if(!unique_arr.some(x => x.firstname === obj.firstname)) {
unique_arr.push(obj)
}
return unique_arr;
}, [])
);
答案 3 :(得分:0)
2班轮怎么样。
var ar = [{firstName: 'Jo'}, {firstName: 'Bill'}, {firstName: 'Bill'}];
var firstNames = [];
var uniqueFirstName = ar.filter(obj =>
firstNames.indexOf(obj.firstName) > -1
? false : firstNames.push(obj.firstName))
console.log( JSON.stringify(uniqueFirstName));
答案 4 :(得分:0)
答案似乎是要检查结果数组是否具有值,但是对于唯一性,我发现使用对象并始终设置值更容易,更易于管理,而无需检查它。这依赖于对象可能只有唯一键的前提:
var arr = [{
firstName: "Amy",
lastName: "Adams"
},
{
firstName: "Bryan",
lastName: "Heart"
},
{
firstName: "Amy",
lastName: "Adams"
}
];
var unique = {};
for (var i = 0, n = arr.length; i < n; i++) {
// Key is your unique condition
var key = [arr[i].firstName, arr[i].lastName].join(' ');
unique[key] = arr[i];
}
console.log('Keys:', Object.keys(unique)); // only shown for austerity
console.log('Values:', Object.values(unique));
&#13;
答案 5 :(得分:0)
我将过滤并保留一组已经出现的thr名:
const names = new Set();
const result = array.filter(({ firstName }) => !names.has(firstName) && names.add(firstName));