如何检查数组中的模式?

时间:2016-11-10 16:44:35

标签: javascript arrays

如何在与模式匹配的内容中返回索引数组。

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中。

注意:这些字母不一定是那个顺序。

2 个答案:

答案 0 :(得分:0)

使用Array#forEachArray#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.reduceArray.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"));