数组去重方法

1. new Set( ) 方法去重

var arr = [1, 2, 2, 4, 4, 3, 5, 3, 6, 7, 9];
var newArray= [...new Set(arr)];
var arr = [1, 2, 2, 4, 4, 3, 5, 3, 6, 7, 9];
var arr1 = new Set(arr);
var newArr = Array.from(arr1);

2. filter( ) 方法去重

var arr = [1, 2, 2, 4, 4, 3, 5, 3, 6, 7, 9];
var newArr=arr.filter((elem,i,arr)=>arr.indexOf(elem)===i);

3. hash + 遍历数组 方法去重

var hash = {};
arr.forEach((elem, i, arr) => hash[arr[i]] = 1);
console.log(hash); //{1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 9: 1}
var arr1 = Object.keys(hash);
console.log(arr1);
var newArr = arr1.map((elem) =>(elem - 0));
console.log(newArr);

上一篇:c语言_Day5_07-01


下一篇:前端基础(三十六、ES6 扩展运算符)