数组去重的四种方式

时间:2023-01-30 08:36:29
// 删除重复的
function only(arr){
for(var i=0;i<arr.length;i++){
for(var j = i+1;j<arr.length;j++){
if(arr[i]===arr[j]){
arr.splice(j,1);
j--;
}
}
}
return arr;
}
console.log(only([6]));//[6]
console.log(only([1,9,8,8,0,6,0,6]));//[1, 9, 8, 0, 6]


// 往新数组中插入不重复的元素或在最后一个位置的重复元素
function only(arr){
var newArr = [],
len = arr.length;
for(var i = 0;i<len;i++){
for(var j = i+1;j<len;j++){
if(arr[i]===arr[j]){
j = false;
break;
}
}
if(j){
newArr.push(arr[i]);
}
}
return newArr;
}
console.log(only([6]));//[6]
console.log(only([1,9,8,8,0,6,0,6]));//[1, 9, 8, 0, 6]


//往新数组中插入不重复的元素或在最后一个位置的重复元素
//难理解一些,关键是“j = ++i;”,相当于开启新一轮的i循环(外层循环)
function only(arr){
var newArr = [],
len = arr.length;
for(var i = 0;i<len;i++){
for(var j = i+1;j<len;j++){
if(arr[i] === arr[j]){
j = ++i;
}
}
newArr.push(arr[i]);
}
return newArr;
}
console.log(only([6]));//[6]
console.log(only([1,9,8,8,0,6,0,6]));//[1, 9, 8, 0, 6]

//将数组元素设为对象属性,值为true;如重复,不再添进数组
function only(arr){
var newArr = [],
obj = {},
m;
for(var i = 0;(m = arr[i]) !== undefined;i++){
if(!obj[m]){
newArr.push(arr[i]);
obj[m] = true;
}
}
return newArr;
}
console.log(only([6]));//[6]
console.log(only([1,9,8,8,0,6,0,6]));//[1, 9, 8, 0, 6]