js 빠 른 속도 로 배열 을 써 서 무 겁 거나 배열 대상 을 무 겁 게 합 니 다.

1496 단어
const arr = [1, 2, 5, 6, 8, 2, 1, 3, 568, 9, 78, 1, 2, 6, 6, 9, 8, 4, 5];

//new Set key    

console.log(Array.from(new Set(arr)));
console.log([... new Set(arr)]);

//for of  Object
function distinct(a = [], b = []) {
    let arr = a.concat(b);
    let result = [];
    let obj = {};

    for (let i of arr) {
        if (!obj[i]) {
            result.push(i);
            obj[i] = 1;
        }
    }

    return result
}

console.log(distinct([12, 12, 1], [12, 5]));

//MAp + filter
const seen = new Map();
const result = arr.filter((a) => !seen.has(a) && seen.set(a, 1));
console.log(result);

// filter + indexOf
const result3 = arr.filter((item,index,arr) => arr.indexOf(item) === index);
console.log(result3);

//      
const arr2 = [{
    key: '1',
    value: '111'
}, {
    key: '2',
    value: '222'
}, {
    key: '3',
    value: '333'
},{
    key: '4',
    value: '444'
},{
    key: '1',
    value: '112'
}];

//for of  Object
function distinctObj(arr,key) {
    let result = [];
    let obj = {};

    for (let i of arr) {
        if (!obj[i[key]]) {
            result.push(i);
            obj[i[key]] = 1;
        }
    }

    return result
}

console.log(distinctObj(arr2,'key'));

//MAp + filter
const seen2 = new Map();
const result2 = arr2.filter((a) => !seen2.has(a['key']) && seen2.set(a['key'], 1));
console.log(result2);

좋은 웹페이지 즐겨찾기