|
| 1 | +const arrayWithDuplicates = [1, 2, 3, 4, 2, 3, 5, 6, 1]; |
| 2 | +const uniqueArray = [...new Set(arrayWithDuplicates)]; |
| 3 | + |
| 4 | +console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6] |
| 5 | + |
| 6 | +// Using filter and indexOf: |
| 7 | +const arrayWithDuplicates = [1, 2, 3, 4, 2, 3, 5, 6, 1]; |
| 8 | +const uniqueArray = arrayWithDuplicates.filter((value, index, self) => self.indexOf(value) === index); |
| 9 | + |
| 10 | +console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6] |
| 11 | + |
| 12 | +//Using reduce: |
| 13 | + |
| 14 | +const arrayWithDuplicates = [1, 2, 3, 4, 2, 3, 5, 6, 1]; |
| 15 | +const uniqueArray = arrayWithDuplicates.reduce((accumulator, currentValue) => { |
| 16 | + if (!accumulator.includes(currentValue)) { |
| 17 | + accumulator.push(currentValue); |
| 18 | + } |
| 19 | + return accumulator; |
| 20 | +}, []); |
| 21 | + |
| 22 | +console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6] |
| 23 | + |
0 commit comments