过滤对象数组并使用纯Javascript返回过滤后的数组?

时间:2018-08-15 18:01:59

标签: javascript arrays filtering

我正在处理大学的编码问题,无法解决。

如何仅从使用内置方法将JavaScript列为技能的申请人中从上述数组中获取新数组?

该数组如下所示:

const NewApplicants = [
    { name: "Jimmy", skills: ["Docker", "JavaScript", "Ruby"] },
    { name: "Dave", skills: ["AWS", "Python"] },
    { name: "Frankie", skills: ["Azure", "JavaScript"] },
    { name: "Liam", skills: ["Java", "JavaScript"] },
    { name: "Fred", skills: ["JavaScript", "AWS"] },
    { name: "Sara", skills: ["PHP", "AWS"] },
    { name: "Matt", skills: [".Net", "PHP", "Docker"] },
];

...,新数组应如下所示:

const NewJavaScriptApplicants = [
    { name: "Jimmy", skills: ["Docker", "JavaScript", "Ruby"] },
    { name: "Frankie", skills: ["Azure", "JavaScript"] },
    { name: "Liam", skills: ["Java", "JavaScript"] },
    { name: "Fred", skills: ["JavaScript", "AWS"] },
];

2 个答案:

答案 0 :(得分:4)

使用Array#filterArray#includes就像这样:

const NewApplicants = [
    { name: "Jimmy", skills: ["Docker", "JavaScript", "Ruby"] },
    { name: "Dave", skills: ["AWS", "Python"] },
    { name: "Frankie", skills: ["Azure", "JavaScript"] },
    { name: "Liam", skills: ["Java", "JavaScript"] },
    { name: "Fred", skills: ["JavaScript", "AWS"] },
    { name: "Sara", skills: ["PHP", "AWS"] },
    { name: "Matt", skills: [".Net", "PHP", "Docker"] },
];

const JavaScriptApplicants = NewApplicants.filter(e => e.skills.includes("JavaScript"));

console.log(JavaScriptApplicants)

  

filter()方法创建一个新数组,其中所有元素都通过了由提供的功能实现的测试。
  -https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

  

includes()方法确定数组是否包含某个元素,并根据需要返回true或false。
  -https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

答案 1 :(得分:0)

您可以使用int javascript方法来遍历对象并应用以下条件:

n = int(strArrSize[0])
m = int(strArrSize[1])