Javascript regex search on array

Viewed 35

I have an array containing 0x1 string, i need to count how many of them there are with regex

Code:

list = [["0x1","dasdgjadkasfas",123],["0x1","gasdasfdasd",123456]]

regex = (new RegExp("0x1"))

Expected Output: 2

EDIT: Regex was not a requirement, just first thing that came to my mind also found one answer

list = [["0x1","dasdgjadkasfas",123],["0x1","gasdasfdasd",123456]]

filtered = list.filter(element=>element[0]=="0x1")
console.log(filtered.length)

Output is 2, but if any one sees better approach feel free to answer.

1 Answers
list.filter((arr) => arr.some((text) => regex.test(`${text}`))).length;

We make a new array, where we only keep entries where the subarray has at least one match. Array#some returns true when at least one element in the array matches the condition in the callback. Then just find the length of the resulting array

Related