Search code examples
javascriptarraysforeachinclude

Simple solution remove duplicates in JS array. Must use push or pop and forEach


So, I'm still learning, so forgive the simple nature. But I'm trying to write a function called uniq(arr). If it worked it would return a new array without any duplicate values. It should not change the original array.

Here are two test calls which are currently not working. I'm not sure what the error implies > uniq([1, 2, 3]) Expected: [1, 2, 3] but got:

TypeError: undefined is not an object (evaluating 'copy.includes')

> uniq(['a', 'a', 'b']) Expected: ['a', 'b'] but got: TypeError: undefined is not an object (evaluating 'copy.includes')

function uniq(arr) {
  var copy;
  arr.forEach(function(item) {
    if (!copy.includes(item)) {
      push.copy(item);}})
  return copy
}

Solution

  • Set makes an array unique.

    const unique = (arr) => {
      return [... new Set(arr)];
    }
    
    console.log(unique([1, 2, 3, 3, 2, 5]))
    // Output: [1, 2, 3, 5]