【问题标题】:Find which array element exists in a string [duplicate]查找字符串中存在哪个数组元素[重复]
【发布时间】:2019-11-21 05:15:21
【问题描述】:

有没有什么方法或快速的方法可以查看数组中的哪些元素存在于字符串中?

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring';

在本例中,数组中的bar 存在于myString 中,因此我需要在给定myArraymyString 的情况下获取bar

【问题讨论】:

  • 你尝试了什么?

标签: javascript arrays string ecmascript-6


【解决方案1】:

findincludes 一起使用:

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring';

const res = myArray.find(e => myString.includes(e));

console.log(res);

如果要查找字符串中包含的所有项目,请将find 替换为filter

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring-baz';

const res = myArray.filter(e => myString.includes(e));

console.log(res);

如果你想要索引,使用findIndex:

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring';

const res = myArray.findIndex(e => myString.includes(e));

console.log(res);

多个索引有点棘手 - 您必须使用 Array.prototype.keys 方法来保留原始索引,因为 filter 返回带有新索引的新数组:

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring-baz';

const res = [...myArray.keys()].filter((e, i, a) => myString.includes(myArray[e]));

console.log(res);

(您也可以在上述函数中将e 替换为i,但这样做更容易理解,因为我们正在遍历键。)

【讨论】:

  • .filter 为所有
  • 编辑(很多)@JonasWilms。
  • @JackBashford 你的最后一个例子不起作用?
  • 已修复 @Kobe - 也感谢您的索引!
  • 不用担心,索引听起来更好,但英语很奇怪:P
猜你喜欢
  • 2021-01-14
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 2018-05-15
  • 2018-01-21
相关资源
最近更新 更多