溫馨提示×

JavaScript數(shù)組去重有何方法

小樊
81
2024-10-25 16:29:43
欄目: 編程語言

在JavaScript中,有多種方法可以實(shí)現(xiàn)數(shù)組去重。以下是一些常見的方法:

  1. 使用Set對象:
function uniqueArray(arr) {
  return Array.from(new Set(arr));
}

const array = [1, 2, 3, 4, 4, 5, 6, 6];
const unique = uniqueArray(array);
console.log(unique); // 輸出: [1, 2, 3, 4, 5, 6]
  1. 使用filter方法:
function uniqueArray(arr) {
  return arr.filter((item, index) => {
    return arr.indexOf(item) === index;
  });
}

const array = [1, 2, 3, 4, 4, 5, 6, 6];
const unique = uniqueArray(array);
console.log(unique); // 輸出: [1, 2, 3, 4, 5, 6]
  1. 使用reduce方法:
function uniqueArray(arr) {
  return arr.reduce((accumulator, currentValue) => {
    if (!accumulator.includes(currentValue)) {
      accumulator.push(currentValue);
    }
    return accumulator;
  }, []);
}

const array = [1, 2, 3, 4, 4, 5, 6, 6];
const unique = uniqueArray(array);
console.log(unique); // 輸出: [1, 2, 3, 4, 5, 6]
  1. 使用雙重循環(huán):
function uniqueArray(arr) {
  const result = [];
  for (let i = 0; i < arr.length; i++) {
    let isUnique = true;
    for (let j = 0; j < result.length; j++) {
      if (arr[i] === result[j]) {
        isUnique = false;
        break;
      }
    }
    if (isUnique) {
      result.push(arr[i]);
    }
  }
  return result;
}

const array = [1, 2, 3, 4, 4, 5, 6, 6];
const unique = uniqueArray(array);
console.log(unique); // 輸出: [1, 2, 3, 4, 5, 6]

以上方法都可以實(shí)現(xiàn)數(shù)組去重,你可以根據(jù)自己的需求和喜好選擇合適的方法。

0