JavaScript concatenate arrays without duplication not sorting correctly

Viewed 62

I have made a code in JavaScript to concatenate two arrays of names and sort them out without duplicate. When it shows on the screen I don't see the item 0 of my new array. I don't know why, in the console.log I see the item 0 which is "Alice". But, what I actually see on the webpage is 1. William, 2. Beatrice, 3. Charlie, 4. Charlotte, etc.

let nameM = [
  "William",
  "Nathan",
  "Raphael",
  "Sam",
  "Emile",
  "Leo",
  "Pascal",
  "Felix"
];

let nameF = [
  "Charlotte",
  "Sam",
  "Emma",
  "Charlie",
  "Emilie",
  "Pascal",
  "Lea",
  "Beatrice",
  "Alice"
];

let name, list;
name = [];

function newArray(nameM, nameF) {
  nameM.concat(nameF).forEach(item => {
    if (name.indexOf(item) === -1)
      name.push(item);
  });
  return name;
}

console.log(newArray(nameM, nameF));

list = "<ol>";
name.forEach(firstName);
list += "</ol>";
document.getElementById("firstNames").innerHTML = list;

function firstName(values) {
  name.sort();
  list += "<li>" + values + "</li>";
}

2 Answers
  1. First, use the Destructuring assignment to destructure the nameM and nameF array. And add the destructured array in a Set to remove duplicates. Like this,

    const nameList = [...new Set([...nameM, ...nameF])];
    

  1. Now because nameList is an array, we can chain methods on it. So to sort the array we can use the .sort() method on nameList.

    const nameList = [...new Set([...nameM, ...nameF])].sort()
    

  1. At last we will chain another method .forEach() on sort. Select the <ol> element by id (#firstNames) and add the names to it using Template literals.

    const nameList = [...new Set([...nameM, ...nameF])]
      .sort()
      .forEach(
        (i) =>
        (document.getElementById("firstNames").innerHTML += `<li> ${i} </li>`)
      );
    

Finally, we get something like this:

const nameM = [
  "William",
  "Nathan",
  "Raphael",
  "Sam",
  "Emile",
  "Leo",
  "Pascal",
  "Felix",
];

const nameF = [
  "Charlotte",
  "Sam",
  "Emma",
  "Charlie",
  "Emilie",
  "Pascal",
  "Lea",
  "Beatrice",
  "Alice",
];

const nameList = [...new Set([...nameM, ...nameF])]
  .sort()
  .forEach(
    (i) =>
    (document.getElementById("firstNames").innerHTML += `<li> ${i} </li>`)
  );
<ol id="firstNames"></ol>




Some useful resources:


This can be «simplified» like this:

let nameM = [
  "William",
  "Nathan",
  "Raphael",
  "Sam",
  "Emile",
  "Leo",
  "Pascal",
  "Felix"
];

let nameF = [
  "Charlotte",
  "Sam",
  "Emma",
  "Charlie",
  "Emilie",
  "Pascal",
  "Lea",
  "Beatrice",
  "Alice"
];

console.log(

[...nameM, ...nameF].sort()
  
)

Related