Home > Mobile >  How to find all arrays and not just the first occurance using find method in java script?
How to find all arrays and not just the first occurance using find method in java script?

Time:11-29

Here is my code:

const string = `1
00:01:46,356 --> 00:01:49,893
test test test test

2
00:01:50,794 --> 00:01:54,998
test test test red test test

3
00:01:55,199 --> 00:01:58,267
test test red`;

const match = st.split('\n\n').find((e) => e.includes('red'));


console.log(match);

the problem is it returns only the first occurance (the word "red" in 2nd sentence) while there is another "red" in the last sentence. What should I do to get all occurrences?

CodePudding user response:

Using find:

returns the value of the first element in the provided array that satisfies the provided testing function

Instead of find, you can use filter:

const match = string.split('\n\n').filter((e) => e.includes('red'));

const string = `1
00:01:46,356 --> 00:01:49,893
test test test test

2
00:01:50,794 --> 00:01:54,998
test test test red test test

3
00:01:55,199 --> 00:01:58,267
test test red`;

const match = string.split('\n\n').filter((e) => e.includes('red'));
console.log(match);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Just use filter instead of find.

const st = `1
00:01:46,356 --> 00:01:49,893
test test test test

2
00:01:50,794 --> 00:01:54,998
test test test red test test

3
00:01:55,199 --> 00:01:58,267
test test red`;

const match = st.split('\n\n').filter((e) => e.includes('red'));


console.log(match);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related