检查一个javascript数组是否包含另一个数组的所有值

时间:2018-07-10 03:16:58

标签: javascript

如何查找stringB是否包含stringA的所有值?

想象一下,您想从{ var res = "0" Callback { RestService.getSomeStuff.map(r => println("assign " + r.id) res = r.id) }.runNow() println("res " + res) res } 中创建一个新的字符串(stringB,当您从stringA中获取一个值时,它将从stringA中消失,因此您无法使用它两次。 / p>

因此,如果stringA具有重复值,但是stringB仅具有该值之一,则程序应返回stringA

示例输入:

false

示例输出:

stringA = "A B C D"

stringB = "B B C D"

因为false 只有一个“ B”。

示例输入:

stringA

示例输出:

stringA = "apple banana orange mango" stringB = "banana orange"

这里是我所拥有的,但是它在应该返回true时会返回true,谁能告诉我我的逻辑有什么问题或解决方案是什么?谢谢!

false

3 个答案:

答案 0 :(得分:2)

您可以使用myFn遍历数组并检查条件,并使用class SteppedAction { constructor(proUpdater, unbrInterval, slInterval) { this.subactions = []; // missing but presumably exists } getResult(recipient) { this.subactions.push({ action: (a) => {}, prop: 0, // should this be proportion to match executeSubaction? }); return this; } executeSubaction(subaction, proportion, name) { proportion = (typeof(proportion) === "number" && proportion >= 0) ? proportion : 1; this.subactions.push({ action: subaction, proportion: proportion, name: name }); return this; } } const generate = () => { const activeAction = new SteppedAction(); // ui is not defined here. activeAction.executeSubaction(() => ui.progressPanel.show(), 0); // several of these variables are not defined in the code snippet activeAction.executeSubaction((action) => generatePl(subdivs, dist, count, rate, level, action)); } 检查数组是否包含某个元素。

every


另一种选择是将includes变成let arrayContainsArray = (a, b) => { let a_array = a.split(" ") let b_array = b.split(" ") return a_array.every(o => b_array.includes(o)); } console.log(arrayContainsArray('two times three is not four', 'two times two is four')); console.log(arrayContainsArray('two times two is four', 'two times two is four'));。使用b_array检查集合中是否包含某个元素。

new Set

答案 1 :(得分:2)

您的代码不起作用,因为它总是在第一次迭代中返回任何内容(如果不是false,则为true)(原因:return true语句位于for循环中)。试试这个:

let arrayContainsArray = (a, b) => {
  let a_array = a.split(" ")
  let b_array = b.split(" ")

  for (let i = 0; i < b_array.length; i++) {
    if (a_array.includes(b_array[i])) {
      let index = a_array.indexOf(b_array[i])
      a_array.splice(index, 1)
    } else {
      return false
    }
  }
  return true
}

console.log(arrayContainsArray('two times three is not four', 'two times two is four'));
console.log(arrayContainsArray('A B C D', 'B B C D'));
console.log(arrayContainsArray('apple banana orange mango', 'banana orange'));

答案 2 :(得分:0)

使用jquery和inArray共享我的方法。

// created function
function existAll(baseArray, arrayToCompare) {
var result = true;       

$.each(baseArray, function (ix, data) {
    if (!($.inArray(data, arrayToCompare) !== -1)) {
        result = false;
        return false;
    }
});

return result;

}

// usage
alert(existAll([1,2,3,4],[1,2,3,5,4]));