Muirik
Muirik

Reputation: 6289

Matching Contents from One Array to Another And Returning the Filtered Array

I am trying to check values from one array against another array, and return a filtered array of just the matches.

So, for instance, I can do this to do a boolean check to see if there are matches:

let targetArray = [{"_id" : "111", city: "Los Angeles"}, {"_id" : "222", city: "New York", }, {"_id" : "333", city: "Seattle"}]

let filterValues = ["111", "333"];

let matchCheck = filterValues.every(el => targetArray.some(({_id}) => el == _id))
console.log(matchCheck) // returns true in this case

This returns true because there are matches.

But how would I return an array of just the two marching objects from the original targetArray? In other words, an array that looks like this:

[{"_id" : "111", city: "Los Angeles"}, {"_id" : "333", city: "Seattle"}]

Upvotes: 0

Views: 39

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386654

Driving the using of a Set to the max, you could use a closure over the set and take the obejct, separate the value for cheking with the set and return the result of it.

let targetArray = [{ _id: "111", city: "Los Angeles" }, { _id: "222", city: "New York" }, { _id: "333", city: "Seattle" }],
    filterValues = ["111", "333"],
    filtered = targetArray.filter(
        (s => o => s.has(o._id))
        (new Set(filterValues))
    );

console.log(filtered);

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

Using a Set as this argument of filter()

let targetArray = [{"_id" : "111", city: "Los Angeles"}, {"_id" : "222", city: "New York", }, {"_id" : "333", city: "Seattle"}]

let filterValues = ["111", "333"];

let filtered = targetArray.filter(function({_id}){ return this.has(_id)}, new Set(filterValues))

console.log(filtered)

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

Try this.

let targetArray = [{"_id" : "111", city: "Los Angeles"}, {"_id" : "222", city: "New York", }, {"_id" : "333", city: "Seattle"}]

let filterValues = ["111", "333"];

let op = targetArray.filter(e => {
  return filterValues.includes(e._id)
})

console.log(op)

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816600

But how would I return an array of just the two marching objects from the original targetArray?

By using .filter + .some:

targetArray.filter(({_id}) => filterValues.some(el => el === _id));

You can also use a Set instead of an array to avoid .some:

let filterValues = new Set(["111", "333"]);
targetArray.filter(({_id}) => filterValues.has(_id));

Upvotes: 1

Related Questions