uniapp从数组中删除重复项

发布于:2024-05-08 ⋅ 阅读:(33) ⋅ 点赞:(0)

在 UniApp(或任何使用 JavaScript 的环境中)从数组中删除重复项,你可以使用多种方法。以下是一些常见的方法:

1. 使用 filter()indexOf()

你可以使用 Array.prototype.filter() 方法结合 Array.prototype.indexOf() 方法来创建一个新数组,该数组只包含原始数组中的唯一元素。

let arr = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Alice' }, // 重复项
  // ...
];

// 假设我们要根据 'id' 属性去重
let uniqueArr = arr.filter((item, index, self) => {
  return self.findIndex(t => t.id === item.id) === index;
});

console.log(uniqueArr);

2. 使用 Set 对象和 JSON.stringify()

如果你的对象可以安全地转换为字符串(即它们的属性顺序不重要,且没有函数或循环引用),你可以先将对象转换为字符串,然后使用 Set 对象来去重,最后再将字符串转回对象。但请注意,这种方法可能不适用于包含复杂数据结构的对象。

let arr = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Alice' }, // 重复项
  // ...
];

let uniqueArr = [...new Set(arr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));

console.log(uniqueArr);

3. 使用 reduce() 方法

你也可以使用 Array.prototype.reduce() 方法来创建一个新的数组,其中只包含唯一的元素。

let arr = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Alice' }, // 重复项
  // ...
];

let uniqueArr = arr.reduce((accumulator, currentValue) => {
  const existing = accumulator.find(item => item.id === currentValue.id);
  if (!existing) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);

console.log(uniqueArr);

4. 使用第三方库(如 lodash 的 _.uniqBy

如果你在使用像 lodash 这样的第三方库,你可以使用其提供的 _.uniqBy 方法来根据指定的属性去重。

首先,你需要安装 lodash:

npm install lodash --save

然后,在你的代码中:

import _ from 'lodash';

let arr = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Alice' }, // 重复项
  // ...
];

let uniqueArr = _.uniqBy(arr, 'id');

console.log(uniqueArr);

选择哪种方法取决于你的具体需求,比如性能、可读性和代码库的现有依赖。如果你正在处理大量数据或性能是一个关键考虑因素,那么你应该测试不同的方法以确定哪种方法在你的特定情况下最有效。