gpt4 book ai didi

javascript - 检查数组是否包含任何另一个字符串数组

转载 作者:行者123 更新时间:2023-11-30 09:35:39 24 4
gpt4 key购买 nike

strings_to_check = ["a", "b", "c"]

test_arrrays = [ [ "a", "c", "e", "g"], [ "v", "x", "y", "z"] ]

检查 test_arrays 中的每个数组是否包含 strings_to_check 数组中的字符串的 any 的正确方法是什么 - 即。 a、b 或 c

我可以执行以下操作,但它有一个缺点,即即使其中一个字符串存在,它仍会检查其余字符串。

for(let i = 0; i < test_arrrays.length; i++){
for(let j = 0; j < strings_to_check.length; j++){
if(test_arrrays[i].indexOf(strings_to_check[j]) > -1) {
console.log("matched");
}
}
}

最佳答案

这可以通过高阶函数更简单地完成,而不是转而使用 for 循环和大量索引。

  1. 我们想看看是否所有的 test_arrrays 元素都满足一些标准,所以我们知道我们应该使用 every:

    test_arrrays.every(/* some criteria */);
  2. 现在我们只需找出该标准是什么。 "contains any of the strings in strings_to_check"听起来我们需要在 test_array 上使用 some 来查明它的任何字符串是否包含在 strings_to_check。所以我们的“标准”将是:

    test_arrray => test_arrray.some(s => strings_to_check_set.includes(s))

    把它放在一起,我们得到:

    test_arrrays.every( test_arrray => 
    test_arrray.some(s => strings_to_check_set.includes(s))
    )
  3. includes 具有线性时间复杂度,因此我们可以通过使用 Set 并将 includes 替换为 来改进此算法>has,具有常数时间复杂度。,得到这个最终结果:

    strings_to_check = ["a", "b", "c"]

    test_arrrays = [ [ "a", "c", "e", "g"], [ "v", "x", "y", "z"] ]

    strings_to_check_set = new Set(strings_to_check)

    test_arrrays.every(test_arrray =>
    test_arrray.some(s => strings_to_check_set.has(s))
    )

关于javascript - 检查数组是否包含任何另一个字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43723758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com