如何判断数组是否包含任何子字符串 [英] how to tell if an array includes any of the substrings

查看:74
本文介绍了如何判断数组是否包含任何子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含javascript字符串的数组,看起来像这样:

I have an array with javascript strings that looks something like this:

let array = ['cat', 'dog', 'bird']

并且我的字符串中有一些用 | 分隔的单词这是字符串:

and I have some words inside my string that are separated by a | this is the string:

let string = 'pig|cat|monkey' 

那么我怎么知道我的数组中的字符串中是否至少包括这些项之一?

so how do I know if my array includes at least one of these items within my string?

推荐答案

您可以使用Array方法 .some()

You can check if an animal from the array exists in the string using an Array method .some()

const animals = ['cat', 'dog', 'bird']
const string = 'pig|cat|monkey'
const splitString = string.split('|')


const hasAnimals = animals.some(animal => splitString.includes(animal))

您可以使用Array方法 .reduce()

You can get the animals that are present using an Array method .reduce()

const presentAnimals = splitString.reduce((acc, animal) => {
  const animalExists = animals.includes(animal)
  if (animalExists) {
    acc.push(animal)
  }
  return acc
}, [])

或者,如果您喜欢一支班轮

Or if you prefer a one liner

const presentAnimals = splitString.reduce((acc, animal) => animals.includes(animal) ? [...acc, animal] : [...acc], [])

这篇关于如何判断数组是否包含任何子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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