I have been looking for a javascript function that remove duplicate values in array.
I found this function:
function removeDuplicateElement(arrayName)
{
var newArray=new Array();
label:for(var i=0; i<arrayName.length;i++ )
{
for(var j=0; j<newArray.length;j++ )
{
if(newArray[j]==arrayName[i])
continue label;
}
newArray[newArray.length] = arrayName[i];
}
return newArray;
}
which is what i need.
Can someone explain me how this function actually work and for what that ‘label:’ is?
I cant understand the logic of this code and if someone can give me an explanation it will be great. 10x
In JavaScript, you can specify a
label:as a location to jump to in acontinueorbreakstatement. So when thecontinueis reached, the iteration returns to the outer for loop instead of the inner loop where it resides (which would be the default behavior ofcontinue)Basically, this function works by making a new array
newArray(not modifying the old one) and looping over every element in the original array. It adds the element from the original array to thenewArrayif not already found. It determines if it already is present innewArrayby looping over that it for each iteration of the old array’s loop and looking for the matching valuearrayName[i]For more information on the function of the
continuein this context, have a look at the MDN documentation.