如何在与模式匹配的内容中返回索引数组。
var contents = ["Dog is big","Cat is small","Horse is huge"]
(contents,"og") //returns [0,2]
(contents,"at") //returns [1]
(contents,"..") //etc
因此,“o”和“g”都在0和2中,但不在1中。
注意:这些字母不一定是那个顺序。
答案 0 :(得分:0)
使用Array#forEach
和Array#every
方法。
var contents = ["Dog is big", "Cat is small", "Horse is huge"]
console.log(get(contents, "og"));
console.log(get(contents, "at"));
console.log(get(contents, ".."));
function get(arr, str) {
// array for storing result
var res = [];
// iterate over string array
arr.forEach(function(v, i) {
// split string into individual character and
// check for each for match
// if all elements matched push the element
if (str.split('').every(function(v1) {
return v.indexOf(v1) > -1;
}))
res.push(i);
});
return res;
}
答案 1 :(得分:0)
您可以使用Array.prototype.reduce
和Array.prototype.every
过滤掉符合条件的指数 - 请参阅下面的演示:
var contents = ["Dog is big","Cat is small","Horse is huge"];
function filter(filter) {
var f = filter.split('');
return contents.reduce(function(p,c,i){
f.every(e=>~c.indexOf(e)) && p.push(i);
return p;
},[]);
}
console.log(filter("og"));
console.log(filter("at"));