可以使用 Array.prototype.filter() 方法来过滤数组中元素的某个属性与其他属性相等的元素。

例如,如果我们有一个包含对象的数组,每个对象都有一个属性 name 和一个属性 age,我们想要过滤掉那些 name 和 age 相等的元素,可以这样做:

const arr = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 },
  { name: 'David', age: 35 }
];

const filteredArr = arr.filter((item, index, self) => {
  return self.findIndex((obj) => {
    return obj.name === item.name && obj.age === item.age;
  }) === index;
});

console.log(filteredArr);
// Output: [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'David', age: 35 }]

上面的代码中,我们使用了两个方法:Array.prototype.filter() 和 Array.prototype.findIndex()。

filter() 方法接受一个函数作为参数,这个函数会被调用数组中的每个元素,如果函数返回 true,则该元素将被保留,否则将被过滤掉。在我们的例子中,我们传递了一个匿名函数,它使用 findIndex() 方法来查找数组中是否存在一个与当前元素相同的元素。如果不存在,则返回当前元素的索引,否则返回找到的元素的索引。由于我们只想保留第一个找到的元素,所以我们可以比较它的索引与当前元素的索引是否相等。如果相等,则说明当前元素是唯一的,应该被保留。

最终结果是一个新的数组,包含不重复的元素

js 将数组中元素的某个属性与其他属性相等的过滤掉

原文地址: http://www.cveoy.top/t/topic/g7f7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录