Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vanilla Javascript unique numbers in array with reduce and find

Tags:

javascript

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.

like image 683
StandardNerd Avatar asked Jan 27 '26 04:01

StandardNerd


1 Answers

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));
like image 58
Nina Scholz Avatar answered Feb 02 '26 15:02

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!