I'm trying to achieve to write an array function with the use of reduce and find helpers that returns an array of unique numbers.
var numbers = [1, 1, 2, 3, 4, 4];
// function should return [1, 2, 3, 4]
function unique(array) {
array.reduce((uniqueArray, number) => {
if (uniqueArray.indexOf(find(array.number))) {
uniqueArray.push(array.number);
}
return uniqueArray;
}, []);
}
console.log(unique(numbers));
// undefined
// undefined
When running this code I get
undefined
twice in Browser Javascript console.
You need a return statment.
return array.reduce((uniqueArray // ...
// ^^^
And some better find method with Array.indexOf
function unique(array) {
return array.reduce((uniqueArray, number) => {
if (uniqueArray.indexOf(number) === -1) {
uniqueArray.push(number);
}
return uniqueArray;
}, []);
}
var numbers = [1, 1, 2, 3, 4, 4];
console.log(unique(numbers));
And now with Set and spread syntax ... for collecting the items in a new array.
function unique(array) {
return [... new Set(array)];
}
var numbers = [1, 1, 2, 3, 4, 4];
console.log(unique(numbers));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With