<!DOCTYPE html>
<html lang="zh"> <head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>JavaScript 数组去重 面试题</title>
</head> <body>
<script type="text/javascript">
var arr = [1, 2, 3, 4, 1, 2, 5];
//方法一:ES6 set
var newArr = [...(new Set(arr))];
console.log(newArr);
//方法二:
function dicArr(arr) {
var newArr = [];
for(var i = 0, len = arr.length; i < len; i++) {
if(newArr.indexOf(arr[i]) == -1) {
newArr.push(arr[i]);
}
}
return newArr;
}
console.log(dicArr(arr));
//方法三
function dicArr2(arr) {
var newArr = [],
obj = {};
for(var i = 0, len = arr.length; i < len; i++) {
if(!obj[arr[i]]) {
obj[arr[i]] = 1;
newArr.push(arr[i]);
}
}
return newArr;
}
console.log(dicArr2(arr));
//方法四
function dicArr3(arr) {
for(var i = 0, len = arr.length; i < len; i++) {
for(var j = i + 1; j < len; j++) {
if(arr[i] == arr[j]) {
arr.splice(j, 1);
len--;
j--;
}
}
}
return arr;
}
console.log(dicArr3(arr));
//方法五 说明使用map,filter,forEach都行
function dicArr4(arr) {
var newArr = [];
// arr.forEach(function(value,key,arr){
// var flag = arr.indexOf(value,key+1);
// if(flag == -1){
// newArr.push(value);
// }
// });
// arr.map(function(value, key, arr) {
// var flag = arr.indexOf(value, key + 1);
// if(flag == -1) {
// newArr.push(value);
// }
// });
arr.filter(function(value, key, arr) {
var flag = arr.indexOf(value, key + 1);
if(flag == -1) {
newArr.push(value);
}
});
return newArr;
}
console.log(dicArr4(arr));
</script>
</body> </html>
上述一共实现五种数组去重方法。