博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数组去重(至少两种方法)js
阅读量:4128 次
发布时间:2019-05-25

本文共 2880 字,大约阅读时间需要 9 分钟。

方法1:普通版,利用indexOf去重

新建一个数组,遍历去要重的数组,当值不在新数组的时候(indexOf为-1)就加入该新数组中。

  • indexOf() 方法:返回某个指定的字符串值在字符串中首次出现的位置。如果要检索的字符串值没有出现,则该方法返回 -1。
//方法1:普通版,利用indexOf去重function arrayUnique(arr){    var len = arr.length;    var res = [];    for(var i = 0; i < len; i++) {        if(res.indexOf(arr[i]) === -1) {  //如果该数之前没有出现过            res.push(arr[i]);  //就把该元素push进去        }    }    return res;}var arr = [1, 1, 'hi', 'true', 'true', true, 15, 15, 15];console.log(arrayUnique(arr));  //[ 1, 'hi', 'true', true, 15 ]

 

方法2:利用Map去重

创建一个空Map数据结构,遍历需要去重的数组,把数组的每一个元素作为key存到Map中。由于Map中不会出现相同的key值,所以最终得到的就是去重后的结果。

Map是ES6 提供的新的数据结构。 

Map 对象保存键值对。任何值(对象或者原始值) 都可以作为一个键或一个值。以下是Map对象的方法:

// 方法2:hashMapfunction arrayUnique2(arr) {    let res = [];  // 结果数组    let map = new Map();    for (let i = 0; i < arr.length; i++) {        if(!map.get(arr[i])) {  //若果hashMap中还没有该key值            map.set(arr[i], 1);            res.push(arr[i]);        }    }    return res;}var arr = [1, 1, 'hi', 'true', 'true', true, 15, 15, 15];console.log(arrayUnique2(arr));  //[ 1, 'hi', 'true', true, 15 ]

 

方法3:利用Set去重

Array.from( set对象 )  可以把set转成数组。

ES6 新增了 Set 这一数据结构,类似于数组,区别在于它所有的成员都是唯一的,不能有重复的值

  • Array.from() 方法:从一个类似数组或可迭代的对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等) 中创建一个新的数组实例。

语法:

Array.from(arrayLike[, mapFn[, thisArg]])

示例代码:

const bar = ["a", "b", "c"];Array.from(bar);// ["a", "b", "c"]Array.from('foo');// ["f", "o", "o"]

//方法3:使用 Set 进行数组去重// 使用 Set 完成 数组去重,只能去除字符串和数字的重复,不能去除对象的重复  function uniqueSet(array) {    return Array.from(new Set(array));}//或function uniqueSet2(array) {    return [...new Set(array)];  // 用...(展开操作符)操作符将Set转换为Array                                 // 用 [...A] 将 A 转换为数组}var arr = [1, 1, 'hi', 'true', 'true', true, 15, 15, 15];console.log(uniqueSet(arr));  //[ 1, 'hi', 'true', true, 15 ]

 

方法4:使用 filter

将两个数组拼接为一个数组,然后使用 ES6 中的 Array.filter() 遍历数组,并结合 indexOf 来排除重复项。

  • filter() 方法:创建一个新的数组,新数组中的元素 是 通过检查 指定数组 中 符合条件的所有元素。
  • indexOf() 方法:可返回某个指定的字符串值在字符串中首次出现的位置。

语法

array.filter(function(currentValue,index,arr), thisValue)

参数说明:

这里写图片描述

语法

array.indexOf(item,start)

参数值

参数 描述
item 必须。查找的元素。
start 可选的整数参数。规定在数组中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。
// 方法4:使用 filterfunction uniqueFilter(arr) {    var res = arr.filter(function(item, index, array) {        // 从数组0位开始查,如果当前元素在原始数组中的第一个索引 === 当前索引值,说明它是第一次出现        return array.indexOf(item) === index;    });    return res;}var arr = [1, 1, 'hi', 'true', 'true', true, 15, 15, 15];console.log(uniqueFilter(arr));  //[ 1, 'hi', 'true', true, 15 ]

 

方法5和方法6

// 方法5:原型方法Array.prototype.unique = function () {  const newArray = [];  this.forEach(item => {    if (newArray.indexOf(item) === -1) {      newArray.push(item);    }  });  return newArray;} // 方法6:精简版 使用 filter 和 indexOf 结合实现Array.prototype.unique = function () {  return this.filter((item, index) => {    return this.indexOf(item) === index;  })}

 

你可能感兴趣的文章
浅谈JavaScript的语言特性
查看>>
LeetCode第39题思悟——组合总和(combination-sum)
查看>>
LeetCode第43题思悟——字符串相乘(multiply-strings)
查看>>
LeetCode第44题思悟——通配符匹配(wildcard-matching)
查看>>
LeetCode第45题思悟——跳跃游戏(jump-game-ii)
查看>>
LeetCode第46题思悟——全排列(permutations)
查看>>
LeetCode第47题思悟—— 全排列 II(permutations-ii)
查看>>
LeetCode第48题思悟——旋转图像(rotate-image)
查看>>
驱动力3.0,动力全开~
查看>>
记CSDN访问量10万+
查看>>
Linux下Oracle数据库账户被锁:the account is locked问题的解决
查看>>
记CSDN访问20万+
查看>>
Windows 环境下Webstorm 2020.3 版本在右下角找不到Git分支切换部件的一种解决方法
查看>>
Electron-Vue项目中遇到fs.rm is not a function问题的解决过程
查看>>
飞机换乘次数最少问题的两种解决方案
查看>>
有向无回路图的理解
查看>>
设计模式中英文汇总分类
查看>>
WPF实现蜘蛛纸牌游戏
查看>>
单例模式
查看>>
工厂方法模式
查看>>