js 数组去重的几种方法

在JavaScript中,有几种常用的方法可以对数组进行去重:

1. 使用Set

使用ES6中引入的Set数据结构,Set只会保留不重复的值,可以很方便地去除数组中的重复元素。
//去重一般数组

const array = [1, 2, 3, 3, 4, 5, 5];

const uniqueArray = [...new Set(array)];

console.log(uniqueArray); // [1, 2, 3, 4, 5]


//去重一个JSON数组

const jsonArray = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 1, name: 'John' },
  { id: 3, name: 'Bob' }
];

const uniqueJsonArray = Array.from(new Set(jsonArray.map(JSON.stringify))).map(JSON.parse);

console.log(uniqueJsonArray);
// Output:
// [
//   { id: 1, name: 'John' },
//   { id: 2, name: 'Jane' },
//   { id: 3, name: 'Bob' }
// ]

2. 使用filter

使用数组的filter方法结合indexOf或includes方法,可以过滤掉数组中的重复元素。
//filter去重一般数组

const array = [1, 2, 3, 3, 4, 5, 5];

const uniqueArray = array.filter((value, index, self) => {
  return self.indexOf(value) === index;
});

console.log(uniqueArray); // [1, 2, 3, 4, 5]


//filter去重json数组

const jsonArray = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 1, name: 'John' },
  { id: 3, name: 'Bob' }
];

const uniqueJsonArray = jsonArray.filter((value, index, self) => {
  return (
    index ===
    self.findIndex(
      item => item.id === value.id && item.name === value.name
    )
  );
});

console.log(uniqueJsonArray);
// Output:
// [
//   { id: 1, name: 'John' },
//   { id: 2, name: 'Jane' },
//   { id: 3, name: 'Bob' }
// ]

3. 使用reduce

使用数组的reduce方法,可以遍历数组并判断当前元素是否已存在于累加器中,如果不存在则添加到累加器中。
//reduce去重一般数组

const array = [1, 2, 3, 3, 4, 5, 5];

const uniqueArray = array.reduce((accumulator, currentValue) => {
  if (!accumulator.includes(currentValue)) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);

console.log(uniqueArray); // [1, 2, 3, 4, 5]


//reduce去重json数组

const jsonArray = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 1, name: 'John' },
  { id: 3, name: 'Bob' }
];

const uniqueJsonArray = jsonArray.reduce((accumulator, currentValue) => {
  const exists = accumulator.some(item => item.id === currentValue.id && item.name === currentValue.name);
  if (!exists) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);

console.log(uniqueJsonArray);
// Output:
// [
//   { id: 1, name: 'John' },
//   { id: 2, name: 'Jane' },
//   { id: 3, name: 'Bob' }
// ]

4. 使用双重循环

通过双重循环遍历数组,比较每个元素与后面的元素,如果有重复的则移除。
const array = [1, 2, 3, 3, 4, 5, 5];

const uniqueArray = [];

for (let i = 0; i < array.length; i++) {
  let isDuplicate = false;
  for (let j = i + 1; j < array.length; j++) {
    if (array[i] === array[j]) {
      isDuplicate = true;
      break;
    }
  }
  if (!isDuplicate) {
    uniqueArray.push(array[i]);
  }
}

console.log(uniqueArray); // [1, 2, 3, 4, 5]

以上是几种常见的数组去重方法。根据具体情况选择合适的方法进行数组去重操作。