javascript 搜索项目并返回在js中的主项目列表中找到的第一个项目

m3eecexj  于 2022-10-30  发布在  Java
关注(0)|答案(2)|浏览(140)

我有两个数组,第一个列表包含了所有名字的主列表:

const masterNames = [
"Adam", 
"Owen",
"Dylan",
"Luke",
"Gabriel",
"Anthony",
"Isaac",
"Grayson",
"Jack",
"Julian",
"Levi",
];

和另一个包含特定名称的列表:

const students = ["Steve", "Dylan", "Luke"]

我想搜索主列表,并返回在主列表中找到的学生的名字。在本例中为“Dylan”,因为Steve不在列表中。

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);
    });

我在循环中使用了Array.prototype.find(),但它返回所有名称,而不仅仅是第一项。

soat7uwm

soat7uwm1#

要查找第一个匹配的单个名称,可以使用find()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);

如果您认为可能需要剩余的匹配名称,则可以通过masterNames数组includes()filter()students数组,并获取结果中的第一个元素,此处使用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);
7hiiyaii

7hiiyaii2#

您可以替换forEach并使用find。

const students = ["Steve", "Dylan", "Luke"];
const masterNames = [
  "Adam",
  "Owen",
  "Dylan",
  "Luke",
  "Gabriel",
  "Anthony",
  "Isaac",
  "Grayson",
  "Jack",
  "Julian",
  "Levi",
];

let found = masterNames.find(function(item) {
  return students.find(element => element === item);
});

console.log(found)

相关问题