比较/过滤两个数组,其中数组B包含A的任何子串 [英] Compare/filter two arrays where array B contains any substring of A

查看:25
本文介绍了比较/过滤两个数组,其中数组B包含A的任何子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这是我比较以下内容的部分工作(忽略大小写):

Okay, so this is something i partially have working (ignoring case sensitivity) comparing the following:

arrayA = ["apples", "Oranges", "salt", "Cracked Black Pepper"];
arrayB = ["salt", "pepper", "orange"]

可部分"与以下内容配合使用:

which works 'partially' with the following:

findAnyMatch(arrayA, arrayB): string[] {
    let returnArray = [];
    let conditionedArrayA = arrayA.map(i => i.toLowerCase().trim())
    for (let i = 0; i < arrayB.length; i++) {
      if (conditionedArrayA .includes(arrayB[i].toLowerCase().trim())) {
        ret.push(arrayB[i].toLowerCase().trim());
      }
    }
    return returnArray;
  }

很高兴地返回:盐",橙色" ;问题在于它在arrayA中看不到辣椒",因为它前面已经裂开了黑色".

Which returns: "salt", "orange" quite happily; the problem being that it can't see "pepper" in arrayA because it has "cracked black" in front of it.

我如何在条件数组A的每个字符串中的任何地方搜索它?

How do i get it to search anywhere inside each string of the conditioned arrayA?

谢谢

推荐答案

您可以使用过滤器等.与正则表达式

You can use filter and some. with regex

  • 过滤器仅用于获取所需的值.
  • 一些用于检查 arrayA 中的任何值是否与当前元素匹配.
  • 正则表达式用于匹配字符串. i 标志用于区分大小写.
  • Filter is used to get desired values only.
  • Some is used to check if any of values in arrayA matches with current element.
  • Regex is used to match the string. i flag is used for case insensitivity.

let arrayA = ["apples", "Oranges", "salt", "Cracked Black Pepper"];
let arrayB = ["salt", "pepper", "orange"]

let find = (A,B) => {
  return B.filter(b=> A.some(a=> new RegExp(b,'i').test(a)))
}

console.log(find(arrayA,arrayB))

这篇关于比较/过滤两个数组,其中数组B包含A的任何子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆