Jake Wilcox
Jake Wilcox

Reputation: 176

Filter an array of objects and return a filtered array using pure Javascript?

I'm working on a coding problem for university and can't figure this out.

How can I get a new array from the above array with only applicants that have JavaScript listed as a skill using builtin methods only?

The array looks like this:

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"] },
];

... and the new array should look like this:

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

Upvotes: 4

Views: 19583

Answers (2)

Haider Ali
Haider Ali

Reputation: 1121

You can use the filter javascript method to loop through the objects and apply this condition:

var filteredData = NewApplicants.filter(function(applicant) {
    return applicant.skills.includes('JavaScript');
});

Upvotes: 2

user4639281
user4639281

Reputation:

Use Array#filter and Array#includes like so:

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)

The filter() method creates a new array with all elements that pass the test implemented by the provided function.
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

The includes() method determines whether an array includes a certain element, returning true or false as appropriate.
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Upvotes: 10

Related Questions