Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"] },
];
like image 558
Jake Wilcox Avatar asked Oct 15 '25 20:10

Jake Wilcox


1 Answers

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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!