过滤数组以获取唯一的字段值

23 浏览
0 Comments

过滤数组以获取唯一的字段值

我知道有很多方法可以过滤数组中的唯一值,但是如何过滤包含给定字段唯一值的对象数组呢?\n例如,我有一个数组[obj1, obj2, obj3, ...],其中每个对象的形式如下:\n

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

\n如何过滤该数组以得到一个最终数组,其中所有对象的名字都是唯一的?最好是一行代码,但不要牺牲可读性。

0
0 Comments

问题的出现原因:

- 需要从一个数组中筛选出具有唯一字段值的对象。

解决方法:

- 使用reduce方法对数组进行处理。

- 设置初始值为一个空数组,并根据条件将对象推入新数组中,条件是该对象的firstname字段不存在于新数组中。

- 返回新数组作为结果。

代码如下:

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;
  }, [])
);

关于为什么在reduce中使用箭头函数,而在内部使用传统的函数表达式的原因:

- 这是无意之中的,并且可能是因为reduce函数的处理函数比内部简单的箭头函数要复杂一些。

以上便是解决"Filter array for unique field values"问题的原因和解决方法。

0
0 Comments

问题:如何从数组中过滤出唯一的字段值?

原因:由于数组中可能存在重复的字段值,需要对数组进行过滤,保留唯一的字段值。

解决方法:

1. 可以将数组转化为Map对象,然后将Map对象的值展开成一个新的数组。

代码示例:

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

2. 如果想保留第一个遇到的对象,需要在设置字段值之前检查Map对象是否已经存在该字段值,仅当不存在时才进行设置。

代码示例:

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

3. 如果想保留最后遇到的对象,可以省略检查步骤,直接进行设置。

代码示例:

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

0
0 Comments

问题的出现原因:在给定的数组中,需要根据指定的条件筛选出只包含唯一字段值的项。

解决方法:通过编写一个函数uniqueBy,该函数接受一个数组和一个用于比较两个项是否相等的条件函数cond。该函数内部使用filter方法和findIndex方法来过滤出只包含唯一字段值的项,并返回一个新数组。

具体实现如下:

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

以上代码的输出结果是只包含唯一firstname字段值的项的新数组。

0