Javascript - 将数组1中的子字符串与数组2中的字符串进行比较>丢弃多个实例

时间:2016-06-30 05:11:35

标签: javascript arrays

我有两个数组。一个数组有这样的句子:

var sentences = [
"Bob goes to the zoo",
"Jim goes to the airport",
"Jenny and Bob go to the beach",
"Jenny goes to the cafe"
]

而另一个的名字是这样的:

var names = [
"Bob",
"Jim",
"Jenny"
]

我想要做的是输出到一个新数组,但只有那些只有一个来自names数组的实例的字符串。 (所以在这个例子中它应该省略“Jenny和Bob去海滩”字符串。

示例输出:

var output = [
"Bob goes to the zoo",
"Jim goes to the airport",
"Jenny goes to the cafe"
]

我知道如果只有一个实例存在但是不太确定如何检查这里需要的多个实例,如何丢弃数组元素:/

3 个答案:

答案 0 :(得分:5)

使用 Array#filter 方法



var sentences = [
    "Bob goes to the zoo",
    "Jim goes to the airport",
    "Jenny and Bob go to the beach",
    "Jenny goes to the cafe"
  ],
  names = [
    "Bob",
    "Jim",
    "Jenny"
  ];


var res = sentences.filter(function(v) { // iterate over sentence array to filter
  return names.filter(function(v1) { // iterate over names array and filter
    return v.indexOf(v1) > -1; // get elements which contains in the sentence
  }).length == 1; // filter based on the filtered names array length
});

console.log(res);




ES6 arrow function



var sentences = [
    "Bob goes to the zoo",
    "Jim goes to the airport",
    "Jenny and Bob go to the beach",
    "Jenny goes to the cafe"
  ],
  names = [
    "Bob",
    "Jim",
    "Jenny"
  ];


var res = sentences.filter(v => names.filter(v1 => v.indexOf(v1) > -1).length === 1);

console.log(res);




更新:如果您想匹配整个单词,可以通过 String#split 方法的简单变体修复它。



var sentences = [
    "Bob goes to the zoo",
    "Jim goes to the airport",
    "Jenny and Bob go to the beach",
    "Jenny goes to the cafe",
  "Patrick says hello to Patricia"
  ],
  names = [
    "Bob",
    "Jim",
    "Jenny",
    "Pat",
    "Patricia"
  ];


var res = sentences.filter(function(v) {
  return names.filter(function(v1) {
    // split based on space for exact word match
    return v.split(/\s+/).indexOf(v1) > -1;
  }).length == 1;
});

console.log(res);




答案 1 :(得分:0)

可以使用filter,split和reduce

var sentences = [
"Bob goes to the zoo",
"Jim goes to the airport",
"Jenny and Bob go to the beach",
"Jenny goes to the cafe"
];

var names = [
"Bob",
"Jim",
"Jenny"
];

// Filter out the sentences
var output = sentences.filter(function(sentence){

  // For each sentence, find number of times of appearance for each name
  return sentence.split(" ").reduce(function(count, word){
    if(names.indexOf(word) >= 0) {
      count += 1;
    }
    return count;
  }, 0) === 1;
});

console.log(output);

答案 2 :(得分:0)

您可以使用for循环,Array.prototype.join()String.prototype.match()

var sentences = [
"Bob goes to the zoo",
"Bob goes to the oz",
"Jim goes to the airport",
"Jim goes to the porch",
"Jenny and Bob go to the beach",
"Jenny goes to the cafe"
]

var names = [
"Bob",
"Jim",
"Jenny"
];

for (var i = 0, s = sentences.join("\n") + "\n", res = []; 
     i < names.length; i++) {
  res.push(s.match(new RegExp(".*(" + names[i] + ").*(?=\n)"))[0])
};

console.log(res);