I have an array of items like this:
const items = ['98 ab','dv 67','96 bh',' 95 df'];
What I am trying is that: to loop over to these items and call a specific functions if the first occurances of the items starts with a number. For example:
if items starts with (98) and then call functionA
and if items starts with (dv) then call functionB
.
const result = items.map(el=>
if(el==='items that starts with number') {
functionA;
} else {
functionB
})
So according to the items array, I should call the functionA three times as there three values that starts with a number in it.
Any ideas how I can achieve it.I need to use Javascript for this. thanks is advance.
4
Answers
If you extract the number from the string, you can use a simple object to map the found number to a function of your liking.
If you only want to search for numbers at the beginning of the string, use the
replace
solution from this answer:Which outputs:
Since I’ve only provided a number in
functionMap
for98
and67
.You can use a regular expression to check if each element in the array starts with a number. If it does, you call functionA; otherwise, you call functionB.
The ^d checks if the string starts with a digit.
I just create a small example, but since you are not transforming the array into a new array, a simple forEach could be more appropriate if you don’t need the result array for other purposes.
You could trim the string and check with a regular expression.
Dont know if it will help. But maybe you can try something like this.