数组去重,数组降级

时间:2023-02-10 23:17:27
var arry = ['1', '3', '2', '1', '4', '2', '1']

es6去重

console.log(new Set(arry))

对象方法去重

function getNewsarry(arr) {
            var hash = {}
            for(var i = 0; i < arr.length; i++) {
                if(!hash[arr[i]]) {
                    hash[arr[i]] = 1;
                }
            }
            return Object.keys(hash)
        }
        console.log(getNewsarry(arry))

双层循环

var arr = [1,23,1,1,1,3,23,5,6,7,9,9,8,5];
function removeDuplicatedItem(arr) {
   for(var i = 0; i < arr.length-1; i++){
       for(var j = i+1; j < arr.length; j++){
           if(arr[i]==arr[j]){
 8              arr.splice(j,1);//console.log(arr[j]);
              j--;
           }
       }
   }
   return arr;
}

arr2 = removeDuplicatedItem(arr);
console.log(arr);
console.log(arr2);

 

除去重复的案例太多了,就不一一列举了

 

数组降级

var arry = [[1, 2],[3, 4]]
 console.log([].concat.apply([],arry))