美文网首页
数组去重有哪些方法?

数组去重有哪些方法?

作者: 祈澈菇凉 | 来源:发表于2023-10-23 09:34 被阅读0次

    在JavaScript中,有几种常用的方法可以对数组进行去重操作。以下是几种常见的数组去重方法:

    1:使用Set数据结构:Set是ES6引入的一种数据结构,它允许你存储唯一的值。通过将数组转换为Set,然后再将Set转换回数组,就可以实现去重。

    const array = [1, 2, 3, 4, 4, 5, 5];
    const uniqueArray = [...new Set(array)];
    console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]
    

    2:使用filter()方法:利用Array的filter()方法,遍历数组并返回满足条件的唯一元素,可以实现数组去重。

    const array = [1, 2, 3, 4, 4, 5, 5];
    const uniqueArray = array.filter((value, index, self) => {
      return self.indexOf(value) === index;
    });
    console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]
    

    3:使用reduce()方法:利用Array的reduce()方法,遍历数组并将不重复的元素添加到结果数组中,可以实现数组去重。

    const array = [1, 2, 3, 4, 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]
    

    4:使用indexOf()方法:遍历数组,在新数组中仅添加不重复的元素,可以实现数组去重。

    const array = [1, 2, 3, 4, 4, 5, 5];
    const uniqueArray = [];
    for (let i = 0; i < array.length; i++) {
      if (uniqueArray.indexOf(array[i]) === -1) {
        uniqueArray.push(array[i]);
      }
    }
    console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]
    

    这些方法都可以实现数组去重的功能。根据具体的需求,选择适合的方法即可。

    相关文章

      网友评论

          本文标题:数组去重有哪些方法?

          本文链接:https://www.haomeiwen.com/subject/zdfnbdtx.html