the murmurous sea

JS: How to remove duplicates from an Array 본문

#dev/개념정리

JS: How to remove duplicates from an Array

lunacer 2020. 5. 13. 21:15

Using Set

    What is Set

더보기

 
    1. collections of values.
    2. store unique values of any type, whether primitive values or object references.

    3. A value in the Set may only occur once; it is unique in the Set's collection.
       : Because each value in the Set has to be unique, the value equality will be checked. 

    4. earlier version of ECMAScript specification, +0 (which is strictly equal to -0) and -0 were different values.
        However, this was changed in the ECMAScript 2015 specification. 
    5. NaN and undefined can also be stored in a Set.
       : All NaN values are equated (i.e. NaN is considered the same as NaN, even though NaN !== NaN)
    6. Set()
       : Creates a new Set object.
     more... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

    solution 1.
    Create a new Set by passing an array to remove duplicates, then convert it back to an array by using the spread operator ...

const array = ['A', 1, 2, 'A', 'A', 3];
const result = [...new Set(array)];

// result = ["A", 1, 2, 3]


    solution 2. 
    use Array.from to convert a Set into an array.

Array.from(new Set(array));
// return ["A", 1, 2, 3]

 

Using filter

    with 2 methods,
    1. filter(): filter out the element only when it return 'false'.
    2. indexOf() : returns the first index of the element.

let array = ['A', 1, 2, 'A', 'A', 3];
array.filter((item, index) => array.indexOf(item) === index);
// return ['A', 1, 2, 3];

 

Using reduce

    with 2 methods,
    1. reduce() : reduce the elements of the array and combine them into a final array based on some reducer function.
    2. includes() : determines whether an array contains a specified element, return a boolean.

    : understood the theory, but the code fails. 

 


@
https://medium.com/dailyjs/how-to-remove-array-duplicates-in-es6-5daa8789641c

 

'#dev > 개념정리' 카테고리의 다른 글

JS: split() vs. join()  (0) 2020.05.14
JS: The Arguments Object  (0) 2020.05.14
JS: String() vs. toString() and valueOf()  (0) 2020.05.13
JS: call() and apply()  (0) 2020.05.13
for...in & for...of  (0) 2020.05.13
Comments