Home:ALL Converter>Remove duplicates from an array in Javascript (without modify the array) - Understand the logic behind

Remove duplicates from an array in Javascript (without modify the array) - Understand the logic behind

Ask Time:2019-03-12T05:07:02         Author:Kaiser Soze

Json Formatter

I started using a website called leetcode and one question is to remove all the duplicates in an array without create a new one. Here is the question https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ My solution was to loop and the check each element against the next one, then if match use splice to remove the duplicated one. it works but not when you have something like [1,1,1,1,1] or [1,1,2,2,2,2,3,3] so I found on github a working code:

var removeDuplicates = function(nums) {
    var i = 0;
    for (var n in nums)
        if (i === 0 || nums[n] > nums[i-1])
            nums[i++] = nums[n];
    return i;
};

This code works and passes all the 160 tests, but I don't understand clearly what is doing, especially the part in nums[i++] = nums[n]; can someone be so kind to help me to understand what this, simple, code is doing? thanks

Author:Kaiser Soze,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/55110417/remove-duplicates-from-an-array-in-javascript-without-modify-the-array-under
yy