I have a big array of strings:
['{{Wanted Value}}', 'true', '{{Wanted Value}}', '{{Wanted Value}} unwanted {{Wanted Value}}', 'false'...]
I want to filter the array and extract every {{Wanted Value}} substring to a new array. If the item in the array contains 2 or more of these substrings, I want to have each of them as a separate item. So the result of the above array would be:
['{{Wanted Value}}', {{Wanted Value}}', {{Wanted Value}}', {{Wanted Value}}']
I wrote the regex I want to use but not sure how to write the filter function correctly:
match(/\{\{(.+?)\}\}/)[0]
Thank you
2 Answers 2
You can try this approach
flatMapis to collect all matched stringsfilteris to get rid of empty results
const data =['{{Wanted Value}}', 'true', '{{Wanted Value}}', '{{Wanted Value}} unwanted {{Wanted Value}}', 'false']
const result = data.flatMap(stringData => stringData.match(/\{\{(.+?)\}\}/g)).filter(stringData => stringData);
console.log(result)
answered May 25, 2022 at 13:50
Nick Vu
15.6k5 gold badges29 silver badges37 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Here is a code which use reduce and string match function to filter the result
let r = ['{{Wanted Value}}', 'true', '{{Wanted Value}}', '{{Wanted Value}}', 'unwanted','{{Wanted Value}}', 'false'];
const result = r.reduce((accumulator, current) => {
return current.match(/\{\{(.+?)\}\}/)? accumulator.concat(current): accumulator;
}, []);
console.log(result);
answered May 25, 2022 at 13:50
Yves Kipondo
5,7031 gold badge22 silver badges34 bronze badges
Comments
lang-js