0

I am doing some online coding challenges and i was wondering if anyone had a better way of writing a solution for this.

Write a function called 'unique' that will remove all duplicates values from an array.

var numbers = [1, 1, 2, 3, 4, 3,9,0,9]; 

 return array.reduce(function(previous, num){

    var checkForRepeat = previous.find(function(x){
      return x === num;
    });

    if(checkForRepeat) {
      return previous;
    } else {
      previous.push(num);
      return previous;
    }
  }, []);
}
unique(numbers);
Great Khan 2016
  • 457
  • 9
  • 22
  • It's maybe not the direct answer for you question, but there are plenty of examples in there: https://stackoverflow.com/questions/39599036/javascript-remove-unique-elements-from-array. While waiting for extremely fast solution, try to check the examples in thread I mentioned. Good luck! – Marcin Sep 22 '18 at 19:03

2 Answers2

7

just do this [...new Set(numbers)]

ashish singh
  • 5,548
  • 2
  • 12
  • 32
3

It can be further optimized by using a Set as lookup of a set is a constant time operation i.e O(1), where as lookup in a array is operation with O(n).

let numbers = [1, 1, 2, 3, 4, 3,9,0,9]; 
function unique(array){
 let set = new Set();
 return array.reduce(function(previous, num){
    if(!set.has(num)){
      previous.push(num);
      set.add(num);
    }
    return previous;
  }, []);
}
numbers = unique(numbers);
console.log(numbers);
amrender singh
  • 7,430
  • 3
  • 20
  • 27