筛选唯一字段值的数组

筛选唯一字段值的数组

问题描述:

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

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