前端面试遇到的算法题目(一)

一 数组去重

解法一

用ES6

var a = [1,2,3,4,1,2]
var b = [...new Set(a)]

解法二

创建新数组,用includes 或者 indexOf

var a = [1,2,3,4,1,2]
var b = []
for(var i=0;i

解法三

先排序,相邻的重复的删除

let ary = [12, 23, 12, 15, 25, 23, 25, 14, 16];
ary.sort((a, b) => a - b);
let str = ary.join('@') + '@';
let reg = /(\d+@)\1*/g;
ary = [];
str.replace(reg, (n, m) => {
    m = Number(m.slice(0, m.length - 1));
    ary.push(m);
});

console.log(ary);

解法四

键值对

let arr = [12, 23, 12, 15, 25, 23, 25, 14, 16];
let obj = {}
for(var i=0;i

更多解法请见
数组去重十种方法

推荐阅读
前端面试遇到的算法问题(二)

你可能感兴趣的:(javascript,前端)