An Array of Different Names

javascript , html , array United States
  • 1 month 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']

  • 1 month 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.

“The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.” - Tom Cargill