Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've been trying to convert the following JS code that uses a for loop to a while loop and/or do-while loop.

var unique = function(array) 
{
  var newArray = []
  array.sort()
  for(var x in array) if(array[x] != array[x-1]) newArray.push(array[x])
  return newArray
}

The code is suppose to return only distinct names from an array of names that repeat. I've been trying to convert the for loop but so far I've been running into problems using this:

do
{
    newArray.push(array[x])
}
while(array[x] != array[x-1])
return newArray;

Can anyone help me? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
176 views
Welcome To Ask or Share your Answers For Others

1 Answer

Is it guaranteed that your names are only going to be duplicated in sequence i.e. is it true that if a name does have a duplicate it will be directly after it? If not, then checking the elements that are directly next to each will not find all the duplicates. You'll have to do a nested for loop or some other n^2 algorithm.

var duplicated = false;
for (int x = 0; x < array.length; x++)
{
    for (int y = 0; y < array.length; y++)
    {
        if (array[x] == array[y])
        {
            duplicated = true;
        }
    }
    if (!duplicated)
    {
        array.push(array[x]);
    }
    duplicated = false;
}
return newArray;

please note, this implementation is very poor but it gets the point across.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...