美文网首页
数组去重

数组去重

作者: 阿亮2019 | 来源:发表于2018-05-28 08:40 被阅读5次

传统方法

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

const unique = function (arr) {
  const uniqueArr = [];
  array.forEach((item) => {
    !uniqueArr.includes(item) && uniqueArr.push(item);
  })
  
  return uniqueArr;
}

console.log(unique(array)); // 1, 5, 2, 3, 4

ES6

const unique2 = function (arr) {
  return [...new Set(array)];
}

console.log(unique2(array)); // 1, 5, 2, 3, 4

扩展

传统方法

const unique3 = function (arr) {
  return arr.filter((item, index) => {
    return arr.indexOf(item) === index; // 1, 5, 2, 3, 4
  })
}

最后再写到 Array.prototype 原型中

Array.prototype.unique = function() {
  return this.filter((item, index) => {
    return this.indexOf(item) === index;
  })
}

console.log(array.unique.apply(array));  // 1, 5, 2, 3, 4

相关文章

  • Array集结号

    实现数组去重的几种方法 数组去重一 数组去重二 利用数组indexof+push实现数组去重 数组去重三 利用对象...

  • 实现数组去重有哪些方式

    简单的数组去重 数组对象去重

  • 数组去重的四种方法

    利用双for循环去重 利用对象数组去重 利用对象数组去重并且记录重复次数 通过创建一个新数组进行数组去重

  • js数组去重、对象数组去重

    普通数组去重 一、普通数组去重 方法一:遍历数组法 方法二:排序法 方法三:对象法 对象数组去重 方法一:将对象数...

  • javascript数组去重,数组对象去重

    利用Reduce去重 function unique(arr) {var obj = {};arr = arr.r...

  • js:数组去重

    数组去重的常见写法: 数组去重封装成方法: es6的数组去重(Array.from):

  • ES6数组去重

    普通数组去重 方法1 方法2 对象数组去重

  • js reduce去重用法

    reduce不仅仅可以数据累加,还可以实现去重效果。 重复次数计算 数组去重 数组对象去重,转为数组 对象去重

  • 数组去重

    传统方法 ES6 扩展 传统方法 最后再写到 Array.prototype 原型中

  • 数组去重

    老题了。。虽然网上一搜一大堆,还是自己想了想,自己动笔写了几种。

网友评论

      本文标题:数组去重

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