0

var removeDuplicates = function(nums) {
    let sorted_arr = [];
    for(x in nums){
        if(!sorted_arr.includes(nums[x]))
            sorted_arr.push(nums[x])
    }
    console.log( sorted_arr)
    return sorted_arr
};

const result = removeDuplicates([1,1,2]);
console.log("result", result);

I/P: [1,1,2] O/P: [ ] stdout: [1,2]

Description: I am trying to create a function which returns a sorted array of numbers with no duplicates. I have created an empty array "sorted_arr" and iterate the "nums" array in which I push a number in the "sorted_arr" if the number is not already present in it. The issue I am facing is when I am returning the "sorted_arr" outside for-loop it is empty; while in console.log, i am getting the the expected result.

2 Answers2

0

This seems like an issue about the outer logic of your application. When I try the code you gave, I get the correct result.

const removeDuplicates = nums => {
  let sorted_arr = [];
  for (const num of nums) {
    if (!sorted_arr.includes(num))
      sorted_arr.push(num)
  }
  console.log(`Stdout: [${sorted_arr}]`)
  return sorted_arr
};

const input = [1, 1, 2];

console.log(`Output: [${removeDuplicates(input)}]`)
Bera Koç
  • 67
  • 4
-1

Please use for/of loop. Below is detailed explanation for the same

  • for - loops through a block of code a number of times.
  • for/in - loops through the properties of an object.
  • for/of - loops through the values of an iterable object.
  • while - loops through a block of code while a specified condition is true.
Dave Newton
  • 158,873
  • 26
  • 254
  • 302