Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter an array with another array with matching characters in javascript

Is it possible to have an array filter another array from matching each character?

I have a set of logs and a filter that look like this:

logs = [{id:1, log: "log1"}], {id:2, log: "log2"}, {id:3, log: "fail"}

filter = ["log"]

it should return

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{id:1, log: "log1"}, {id:2, log: "log2"}]

If my filter were to be

filter = ["1", "fai"]

the output would be

[{id:1, log: "log1"}, {id:3, log: "fail"]

>Solution :

You can use the function Array.prototype.filter along with the function Array.prototype.some in order to filter out the objects that don’t match the filter.

const match = (filter, key, array) => array.filter(o => filter.some(c => o[key].includes(c))),
      array = [{id:1, log: "log1"}, {id:2, log: "log2"}, {id:3, log: "fail"}];

console.log(match(["log"], "log", array));
console.log(match(["1", "fai"], "log", array));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading