I\'m learning JavaScript using W3C and I didn\'t find an answer to this question.
I\'m trying to make some manipulations on array elements which fulfill some conditi
Write a generic function that accepts various conditions:
function array_only(arr, condition) {
hold_test=[]
arr.map(function(e, i) {if(eval(condition)){hold_test.push(e)}})
return(hold_test)
}
Example:
use_array = ['hello', 'go_there', 'now', 'go_here', 'hello.png', 'gogo.log', 'hoho.png']
Usage:
return only elements containing .log extension:
array_only(use_array, "e.includes('.log')")
[ 'gogo.log' ]
return only elements containing .png extension:
array_only(use_array, "e.includes('.png')")
[ 'hello.png', 'hoho.png' ]
return only elements NOT containing .png extension:
array_only(use_array, "!e.includes('.png')")
[ 'hello', 'go_there', 'now', 'go_here', 'gogo.log' ]
return elements containing set of extensions and prefixes:
array_only(use_array, "['go_', '.png', '.log'].some(el => e.includes(el))")
[ 'go_there', 'go_here', 'hello.png', 'gogo.log', 'hoho.png' ]
You can easily pass MULTIPLE CONDITIONS
return all png files that are less than 9 characters long:
array_only(use_array, "e.includes('.png') && e.length<9")
[ 'hoho.png' ]