数组去重

方法1

ar arr = ["a","b","c","a","b","c","c","d","d","d"];
var obj = {};
for(var i=0;i<arr.length;i++){
if(obj[arr[i]]){
obj[arr[i]]++
}else{
obj[arr[i]] = 1
}
}

console.log(obj)  //对象{a:2,b:2;c:3,d:3}

方法2

var newArr = [];
for(var i in obj){
newArr.push(i)
}
console.log(newArr)      

方法3

let arr = [1,2,3,4,4,3,2,4,1,5,6]
    let mySet = new Set(arr);
    let newArr = [];
    for(let i of mySet){
        newArr.push(i);
    }
    console.log(newArr);

手写数组去重

var arr = [2,3,4,5,4,3,2,2,3,3,4,4,5,5,6,6]
var a = norepeat(arr)
console.log(a)
function norepeat(myarr){
var newArr = [];
myarr.forEach(function(v){
if(newArr.indexOf(v) == -1){
newArr.push(v)
}
})
return newArr;
}

有一个从小到大排好序的数组。现输入一个数,要求按原来的规律将它插入数组中

var arr = [1,3,5,7,9];
console.log(insert(arr,5));

function insert(myarr,num){
for(var i=0;i<myarr.length;i++){
if(myarr[i] > num){
break;
}
}
for(var j=myarr.length-1;j>=i;j--){
myarr[j+1] = myarr[j]
}
myarr[i] = num;
return myarr;
}
posted @ 2019-07-23 09:34  进击的三三  阅读(155)  评论(0编辑  收藏  举报