Task is to have a function which takes an array. Then removes elements from the array which are contained more then one time. Finally returns an array with only unique elements.
Here's my solution:
// Duplicates : 4 (3 times), 5, 9 (3 times) => Sum: 5 too much !
let withDuplicates = [1, 2, 3, 4, 4,
4, 5, 5, 6, 7,
8, 9, 9, 9, 10
];
let withoutDuplicates = [];
// -- The actual function ------------------
function removeDuplicates(arr) {
return arr.reduce((unique, current) => {
if (!unique.includes(current)) {
unique.push(current);
}
return unique;
}, []);
}
// ----------------------------------------
withoutDuplicates = removeDuplicates(withDuplicates);
console.log(withDuplicates);
console.log('Length:', withDuplicates.length);
console.log(withoutDuplicates);
console.log('Length:', withoutDuplicates.length);
Using reduce() was what came to my mind for solving the task. And the code has become already quite tight.
Nevertheless: Is there a better solution?
Array.from(new Set(arr))
or[...new Set(arr)]
\$\endgroup\$