[英]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它应该返回
[{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"]
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.您可以使用函数Array.prototype.filter
和函数Array.prototype.some
来过滤掉与过滤器不匹配的对象。
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));
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))
})
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);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.