筛选唯一字段值的数组 [英] Filter array for unique field values

查看:100
本文介绍了筛选唯一字段值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多方法可以过滤数组中的唯一值,但是对于给定字段具有唯一值的对象的过滤数组呢?

I know there's many ways to filter arrays for unique values, but what about filtering arrays for objects with unique values for a given field?

例如我有 [obj1,obj2,obj3,...] 其中每个对象的格式如下:

For example I have [obj1, obj2, obj3, ...] where each object is of the following form:

{
firstName: "...",
lastName: "..."
}

如何过滤数组以最终数组为止所有对象都有唯一的名字?单行会更好,但不会以可读性为代价。

How can I filter the array to end up with a final array where all the objects have unique first names? A one-liner would be better, though not at the cost of readability.

推荐答案

仅过滤那些未找到的项目在数组的早期。我们将 cond 定义为返回是否应将两个项目视为相等。

Filter in only those items which are not found earlier in the array. We'll define cond as returning whether two items should be considered "equal".

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));

这篇关于筛选唯一字段值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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