일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
- react
- Empty
- keyup
- UI
- beforeinput
- node
- Dom
- es6
- modal
- js
- node.js
- keyboardEvent
- a11y
- innerText
- HTML
- innerHTML
- ES5
- Review
- dotenv
- nodeValue
- javascript
- addEventListener
- Temporal dead zone
- TypingEffect
- Event
- CSS
- for loop
- css:position
- textContent
- yet
- Today
- Total
the murmurous sea
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
'#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 |