1. 程式人生 > >數組去重--ES5和ES6

數組去重--ES5和ES6

con concat urn let ret return 基礎上 for ===

思路:把去重後的數組放到一個空數組中

ES5實現:

function uni(arr) {
    var result = [];
    for (var i=0;i<arr.length;i++) {
        if(result.indexOf(arr[i])==-1) {
            result.push(arr[i]);
        }
    }
    return result;
}
var obj = new uni([1,1,1,1,3,4,5]);
console.log(obj);

ES6實現:

function
removal(arr) { return Array.from(new Set(arr)); } var obj = new removal([1,2,3,3,3,3,8,6,4,3]); console.log(obj);

在此基礎上,要求合並數組並去重也很簡單了

Es5:

let arr1 = [1,2,3,4]
let arr2 = [3,4,5,6]
function uni(arr1,arr2) {
    var arr3 = arr1.concat(arr2)
    var arr4 = []
    var len = arr3.length
    
for(var i=0;i<len;i++) { if (arr4.indexOf(arr3[i]) === -1) { arr4.push(arr3[i]) } }return arr4 } console.log(uni(arr1,arr2))

Es6:

let arr1 = [1,2,3,4]
let arr2 = [3,4,5,6]
function uni(arr1,arr2){
    arr1.push(...arr2)
    let arr3 = Array.from(new Set(arr1))
    console.log(arr3)
}
uni(arr1,arr2)

數組去重--ES5和ES6