2

I am new at Programing and learning Javascript by doing some exercises from leetcode.com. I wanted to write a code to remove duplicates in a sorted array. When I use "console.log" at the end of the function to show the final result, I get the expected result. However when I use return (with the same variable) I get a wrong result. Can anybody please tell me, where I went wrong? Hier is my code:

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function (nums) {
  var newNums = []

  if (nums.length == 0) {
    newNums = []
  }

  for (var i = 0; i < nums.length; i++) {

    var curr = nums[i]
    var next = nums[i + 1]
    if (curr != next) {
      newNums.push(curr)
    }
  }

  console.log(newNums)
  return newNums
};

And here is a picture with the code and the results. the green arrow shows the output of (console.log), and the red one shows the output of (return). Thank you in advance! enter image description here

Roi
  • 97
  • 1
  • 6
Hamzah
  • 23
  • 2
  • Before asking questions here search on google also. here is your [answer](https://www.geeksforgeeks.org/remove-duplicates-sorted-array/) – Kunal Tanwar Aug 23 '21 at 08:52
  • Your code works. If you call the function like this `console.log(removeDuplicates([1,2,2,3]))` is returns the same thing as the console.log – thetailor.de Aug 23 '21 at 08:53
  • btw, `if (nums.length == 0)` is superfluous. you could exit early but not assign an array, you already have. – Nina Scholz Aug 23 '21 at 08:55
  • Take a look at [this](https://stackoverflow.com/a/9229932/11542917) solution. – Shannarra Aug 23 '21 at 09:09
  • Thank you all for your replies. I already have seen multiple Ways on how to solve the problem. But this one i wrote myself. I just want to understand, why i have different results in (return ```newNums```) and consloe.log(```newNums```), eventhough they are supposed to return the same answer or am i wrong here. – Hamzah Aug 23 '21 at 10:21
  • @NinaScholz, do you mean I should remove it completely? Or should I write ```if (nums.length == 0){break}```? Or does it slow down the run time? – Hamzah Aug 23 '21 at 14:53

2 Answers2

1

A slightly different approach by keeping the original object reference to the array and mutating the array by copying and adjusting the length of the array.

This approach does not need another array.

It basically checks if the predecessor is unequal to the actual item and copies the item to a new index j. This variable has the final length of the array and truncates the unwanted rest of the array.

function removeDuplicates(array) {
    let j = 0;
    for (let i = 0; i < array.length; i++) {
        if (array[i - 1] !== array[i]) array[j++] = array[i];
    }
    array.length = j;
    return array;
}

console.log(removeDuplicates([0, 1, 1, 2, 2, 2, 2, 3, 4, 5, 5]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Here's how you can remove duplicates in any(sorted or unsorted) array in Javascript

const removeDuplicates = (orignalArray) =>{
  let allUniqueArray=[];
  let repWordArray=orignalArray.slice();
 
  const removeAnElement=(array, elem)=>{
    const index = array.indexOf(elem);
    if (index > -1) {
      array.splice(index, 1);
    }
    return array;
  }
 
  orignalArray.forEach(elem=>{
    if(!allUniqueArray.includes(elem)){
      allUniqueArray.push(elem);
      repWordArray=removeAnElement(repWordArray,elem)
    }
  });
  return allUniqueArray;
};

let array=[1,2,3,3,4,5,6,6,7];
const uniqueArray = removeDuplicates(array);
console.log('array: ',array);
console.log('uniqueArray: ',uniqueArray);
Abdul Azeem
  • 337
  • 4
  • 12
  • Thank you for your help! However the code you have writen removes the duplicated number completly. For example [1,1,1,1] -> it returns [ ]. But, what it should do, is only remove the Duplicates (repetition). The correct answer should be [1]. – Hamzah Aug 24 '21 at 07:44
  • 1
    @Hamzah got your point, I've updated my answer. – Abdul Azeem Aug 24 '21 at 09:08
  • 1
    Perfect. It works now as it should. Thank you for your time and Help! – Hamzah Aug 24 '21 at 11:49