最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to filter array of objects in Javascript - Stack Overflow

programmeradmin6浏览0评论

I am trying to create a function in Javascript, that will allow me to filter the skills which the different candidates have, i have been told that this can be done in Javascript, the function called "filterCandidateBySkill" is where i want to filter the candidates skills, but ive had a look of this and as the skills is in an array i cant find anywhere online how to filter it. a lot of them have filters for single words, but not for arrays.

const newCandidates = [
  { name: "bob", skills: ["JavaScript", "Docker", "Ruby"] },
  { name: "ally", skills: ["Python", "AWS"] },
  { name: "joe", skills: ["JavaScript", "Azure"] },
  { name: "fred", skills: ["JavaScript", "Java"]},
];

function filterCandidateBySkill(candidates, skill) {
  // where im confused
}

I am trying to create a function in Javascript, that will allow me to filter the skills which the different candidates have, i have been told that this can be done in Javascript, the function called "filterCandidateBySkill" is where i want to filter the candidates skills, but ive had a look of this and as the skills is in an array i cant find anywhere online how to filter it. a lot of them have filters for single words, but not for arrays.

const newCandidates = [
  { name: "bob", skills: ["JavaScript", "Docker", "Ruby"] },
  { name: "ally", skills: ["Python", "AWS"] },
  { name: "joe", skills: ["JavaScript", "Azure"] },
  { name: "fred", skills: ["JavaScript", "Java"]},
];

function filterCandidateBySkill(candidates, skill) {
  // where im confused
}

Share Improve this question edited Jun 12, 2018 at 23:20 Programmerr asked Jun 12, 2018 at 23:07 ProgrammerrProgrammerr 1,0413 gold badges10 silver badges11 bronze badges 1
  • 1 What does this question have to do with Java? – CertainPerformance Commented Jun 12, 2018 at 23:07
Add a ment  | 

1 Answer 1

Reset to default 8

JS provides a filter method on arrays.

const newCandidates = [
  { name: "bob", skills: ["JavaScript", "Docker", "Ruby"] },
  { name: "ally", skills: ["Python", "AWS"] },
  { name: "joe", skills: ["JavaScript", "Azure"] },
  { name: "fred", skills: ["JavaScript", "Java"]},
];

function filterCandidateBySkill(candidates, skill) {
  return newCandidates.filter(candidate => candidate.skills.includes(skill));
}

// Get only names
console.log(filterCandidateBySkill(newCandidates, 'JavaScript').map(candidate => candidate.name));

// Get entire objects
console.log(filterCandidateBySkill(newCandidates, 'JavaScript'));

发布评论

评论列表(0)

  1. 暂无评论