数组常用方法

数组去重:

一:from, set

function dedupe(arr) {
    return Array.from(new Set(arr));
}
console.log(dedupe([1, 2, 2, 4])); //[1, 2, 4]

二:forEach, indexOf

var arr11 = [1, 1, 2, 4, 3, 1, 6];
var arr12 = [];
arr11.forEach((data) => {
    arr12.indexOf(data) === -1 && arr12.push(data);
});
console.log('----forEach---', arr12); // [1, 2, 4, 3, 6]

三:reduce

let arr9 = [1,2,1,2,3,5,4,5,3,4,4,4,4];
let result9 = arr9.sort().reduce((init, current)=>{
    if(init.length===0 || init[init.length-1]!==current){
        init.push(current);
    }
    return init;
}, []);
console.log(result9); // [1, 2, 3, 4, 5]

 

四:set ,拓展运算符

let arr8 = [1, 1, 4];
let res_arr = [...new Set(arr8)];
console.log(res_arr); // [1, 4]

数组排序:

一:sort

let arr10 = [1, 4, 5, 6, 1, 2];
console.log(arr10.sort((a, b) => {
    return a - b;
}));
console.log(arr10); // [1, 1, 2, 4, 5, 6]

 

posted @ 2018-09-05 17:02  井凉一一  阅读(217)  评论(0编辑  收藏  举报