An Array of Different Names

javascript , html , array United States
  • 9 months ago

    I have an array of names and I want to push only the different names to the namesArray. So this code should output only name-3, name-4, and name-5

    var names = ["name-1","name-1","name-1","name-1","name-2","name-2","name-3","name-4","name-5","name-6","name-6"];
    
    var namesArray = [];
    for(var i = 0; i < names.length; i++){
    
    product_name = names[i];
    product_name_compare = names[i-1];
    
        if (product_name != product_name_compare){
    
        	namesArray.push(product_name);
        }
    }
    
    console.log(namesArray);
    

    This is the output: [ 'name-1', 'name-2', 'name-3', 'name-4', 'name-5', 'name-6' ]

    Desired output is ['name-3', 'name-4', 'name-5']

  • 9 months ago

    This question was answered at https://codeforum.org/threads/an-array-of-different-names.933/#post-6258 and then I added more complexity to the question.

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“We better hurry up and start coding, there are going to be a lot of bugs to fix.”