1

How do I filter if an array is inside another array?

How should I loop this?

var jobs = [
    {
        'id': '1',
        'departments': [{'name': 'Finance'}],
        'offices': [{'name': 'US'}, {'name': 'Brazil'}]
    },
    {
        'id': '1',
        'departments': [{'name': 'Finance'}],
        'offices': [{'name': 'Paris'}, {'name': 'China'}]
    }
];

var results = jobs.filter(function(o)) {
    return o.offices[0].name == 'US';
} // get office US;

jsFiddle Link

1
  • 3
    jobs.filter(j => j.offices.some(o => o.name === "US")) Use some to see if one of the objects inside the offices array matches your requirement. Commented Jul 3, 2017 at 10:46

1 Answer 1

1

When you want to filter an array by a value that might exist in an internal array, you can use Array#some on the internal array. The method Array#some returns true, and stop iteration, if at least one element of the array meets the criteria.

var jobs = [{"id":"1","departments":[{"name":"Finance"}],"offices":[{"name":"US"},{"name":"Brazil"}]},{"id":"1","departments":[{"name":"Finance"}],"offices":[{"name":"Paris"},{"name":"China"}]}];

var jobsWithoutUs = jobs.filter(function(job) {
  return job.offices.some(function(office) {
    return office.name === 'US';
  });
});

console.log(jobsWithoutUs);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.