admin管理员组文章数量:1333201
I have 2 arrays of keywords. I need to figure out the index of the first keyword in array 1 that matches any of the keywords in array 2.
Examples
array1 = ['spinach', 'avocado', 'milk', 'beans', 'ham', 'eggs', 'cheese'];
array2 = ['cheese', 'milk'];
In this example, milk at index 2 would be the first match, and I want to return the index of 2.
Can I use array.find() to return the index of the first match, if each element is pared to array2 using regex?
I have 2 arrays of keywords. I need to figure out the index of the first keyword in array 1 that matches any of the keywords in array 2.
Examples
array1 = ['spinach', 'avocado', 'milk', 'beans', 'ham', 'eggs', 'cheese'];
array2 = ['cheese', 'milk'];
In this example, milk at index 2 would be the first match, and I want to return the index of 2.
Can I use array.find() to return the index of the first match, if each element is pared to array2 using regex?
Share Improve this question asked Mar 30, 2018 at 19:26 Matthew RideoutMatthew Rideout 8,5865 gold badges48 silver badges71 bronze badges 04 Answers
Reset to default 3You could use Array#findIndex
and check the second array with Array#includes
.
var array1 = ['spinach', 'avocado', 'milk', 'beans', 'ham', 'eggs', 'cheese'],
array2 = ['cheese', 'milk'];
console.log(array1.findIndex(v => array2.includes(v)));
You can find matching index using findIndex()
and includes()
:
let index = array1.findIndex(s => array2.includes(s));
Demo:
let a1 = ['spinach', 'avocado', 'milk', 'beans', 'ham', 'eggs', 'cheese'],
a2 = ['cheese', 'milk'];
let index = a1.findIndex(s => a2.includes(s));
console.log(index);
Docs:
Array.prototype.findIndex()
Array.prototype.includes()
Arrow Functions
Use .findIndex
instead:
const array1 = ['spinach', 'avocado', 'milk', 'beans', 'ham', 'eggs', 'cheese'];
const array2 = ['cheese', 'milk'];
const foundIndex = array1.findIndex(elm => array2.includes(elm));
console.log(foundIndex);
You could create a regular expression from array2
and then use Array.findIndex
:
var re = new RegExp('^'+array2.join('|')+'$');
var found = array1.findIndex(function (e) { return re.test(e); });
本文标签: JavaScript Arrayfind RegexStack Overflow
版权声明:本文标题:JavaScript Array.find Regex - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742287160a2447133.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论