JS: How to remove duplicates from an Array
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