-1

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

[{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"]
CodeNoob
  • 25
  • 1
  • 8
  • 1
    Your question has be answered here https://stackoverflow.com/questions/34901593/how-to-filter-an-array-from-all-elements-of-another-array – Perry Nyakemori Jun 27 '22 at 20:15
  • Does this answer your question? [Javascript: filter array of objects by array of strings](https://stackoverflow.com/questions/28138139/javascript-filter-array-of-objects-by-array-of-strings) – pilchard Jun 27 '22 at 21:12
  • also: [Filter array of objects based on another array in javascript](https://stackoverflow.com/questions/46894352/filter-array-of-objects-based-on-another-array-in-javascript) and [Filter array of objects whose any properties contains a value](https://stackoverflow.com/questions/44312924/filter-array-of-objects-whose-any-properties-contains-a-value) and [Filter array of objects by multiple strings](https://stackoverflow.com/questions/49041678/filter-array-of-objects-by-multiple-strings) – pilchard Jun 27 '22 at 21:12

3 Answers3

4

You can do something like the following:

const logs = [{id:1, log: "log1"}, {id:2, log: "log2"}, {id:3, log: "fail"}]
const searches = ["1", "fai"]
const matchingLogs = logs.filter(l => {
    return searches.some(term => l.log.includes(term))
})
0

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));
Ele
  • 33,468
  • 7
  • 37
  • 75
0
let logs = [{id:1, log: "log1"}, {id:2, log: "log2"}, {id:3, log: "fail"}];

let filter = ["1", "fai"];

/*
 * filter the array using the filter function.  
 * Find any given string in the array of objects.
 * If you have a match, it will be added to the 
 * array that will be returned
 */
let matches = logs.filter(function(object) {
    return !!filter.find(function(elem) {
        return -1 !== object.log.indexOf(elem);
    });
});
Gacci
  • 1,388
  • 1
  • 11
  • 23