1

so im trying to write a function that reads the array and returns a new one without any duplicate numbers, I'm new to JS so could be I wrote a whole bunch of nonsense. the code:

var nums = [5, 4, 5, 7, 1, 9, 4];
removeDuplicates(nums)
function removeDuplicates(nums) {
  var newArray = [];
  for (var i = 0; i < nums.length; i++) {
    switch (nums[i]) {
      case (nums.indexOf(1) !== -1):
        newArray += nums[i];
        break;
      case nums.indexOf(2) !== -1:
        newArray += nums[i];
        break;
      case nums.indexOf(3) !== -1:
        newArray += nums[i];
        break;
      case nums.indexOf(4) !== -1:
        newArray += nums[i];
        break;
      case nums.indexOf(5) !== -1:
        newArray += nums[i];
        break;
      case nums.indexOf(6) !== -1:
        newArray += nums[i];
        break;
      case nums.indexOf(7) !== -1:
        newArray += nums[i];
        break;
      case nums.indexOf(8) !== -1:
        newArray += nums[i];
        break;
      case nums.indexOf(9) !== -1:
        newArray += nums[i];
        break;
      default: break;
    }
  }
  console.log(newArray);
}
A Saban
  • 13
  • 3

2 Answers2

4

Use This

var nums = [5, 4, 5, 7, 1, 9, 4];

var newArray = [...new Set(nums)]
console.log(newArray)

Output:

[ 5, 4, 7, 1, 9 ]
TechySharnav
  • 4,869
  • 2
  • 11
  • 29
1

Without Set

newArray = nums.filter((num, pos) => {
    return nums.indexOf(num) == pos;
})
Vo Quoc Thang
  • 1,338
  • 1
  • 4
  • 5