I have two arrays, the first list contains a master list of all names:
const masterNames = [
"Adam",
"Owen",
"Dylan",
"Luke",
"Gabriel",
"Anthony",
"Isaac",
"Grayson",
"Jack",
"Julian",
"Levi",
];
and another list which contains specific names:
const students = ["Steve", "Dylan", "Luke"]
I want to search the master list and return the first name from students that is found in the master list. In this case "Dylan" since Steve is not on the list.
const students = ["Steve", "Dylan", "Luke"];
const masterNames = [
"Adam",
"Owen",
"Dylan",
"Luke",
"Gabriel",
"Anthony",
"Isaac",
"Grayson",
"Jack",
"Julian",
"Levi",
];
masterNames.forEach(function (item, index) {
const found = students.find(element => element === item);
console.log(found);
});
I used Array.prototype.find()
inside a loop but it returns all name and not just the first item.
CodePudding user response:
To find the first single name that matches you can use find()
and includes()
const students = ["Steve", "Dylan", "Luke"];
const masterNames = ["Adam", "Owen", "Dylan", "Luke", "Gabriel", "Anthony", "Isaac", "Grayson", "Jack", "Julian", "Levi",];
const result = students.find(student => masterNames.includes(student));
console.log(result);
If you think you might need the remaining matching names you can filter()
the students
array by whether the masterNames
array includes()
it and take the first element in the result, here using destructuring assignment
const students = ["Steve", "Dylan", "Luke"];
const masterNames = ["Adam", "Owen", "Dylan", "Luke", "Gabriel", "Anthony", "Isaac", "Grayson", "Jack", "Julian", "Levi",];
const includedStudents = students.filter(s => masterNames.includes(s));
const [result] = includedStudents;
console.log(result);
CodePudding user response:
You can replace forEach and use find.
const students = ["Steve", "Dylan", "Luke"];
const masterNames = [
"Adam",
"Owen",
"Dylan",
"Luke",
"Gabriel",
"Anthony",
"Isaac",
"Grayson",
"Jack",
"Julian",
"Levi",
];
masterNames.find(function (item) {
return students.find(element => element === item);
});