编程语言
首页 > 编程语言> > JavaScript数组去重

JavaScript数组去重

作者:互联网

使用Set对象去重

Set 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用。

var arr = ["apple","apple","banana","banana","pear","pear"];
var mySet = new Set(arr);
console.log([...mySet]); //["apple","banana","pear"]

使用Map对象去重

Map对象存储的是键值对,键值唯一,如果存储时新添加的键重复会出现覆盖

var arr = ["apple","apple","banana","banana","pear","pear"];
var myMap = new Map();
var newArr = [];
for(var i=0;i<arr.length;i++){
    myMap.set(arr[i],i);
}
myMap.forEach(function(value,key){
    ewArr.push(key);
})
console.log(newArr); //["apple", "banana", "pear"]

标签:Map,arr,apple,JavaScript,pear,数组,var,banana
来源: https://www.cnblogs.com/ITwj-115/p/14675022.html