I have an array containing file paths as strings. I need to search through this array & make a new array including only those which contain a certain word. How would I create an if statement that includes the 'includes' method?
Here's my code so far:
var imagePaths = [...]
if(imagePaths.includes('index') === 'true'){
???
}
Thank you in advance
I have an array containing file paths as strings. I need to search through this array & make a new array including only those which contain a certain word. How would I create an if statement that includes the 'includes' method?
Here's my code so far:
var imagePaths = [...]
if(imagePaths.includes('index') === 'true'){
???
}
Thank you in advance
Share Improve this question asked Jul 12, 2017 at 18:35 r_cahillr_cahill 6073 gold badges10 silver badges20 bronze badges3 Answers
Reset to default 13You don't need to compare booleans to anything; just use them:
if (imagePaths.includes('index')) {
// Yes, it's there
}
or
if (!imagePaths.includes('index')) {
// No, it's not there
}
If you do decide to compare the boolean to something (which in general is poor practice), compare to true
or false
, not 'true'
(which is a string).
'true' != true:
if (imagePaths.includes('index') === true) {
???
}
Or, which is way better, just use the value directly, since if
already checks if the expression it receives is equal to true:
if (imagePaths.includes('index')) {
???
}
In Javascript, to make a new array based on some condition, it's better to use array.filter
method.
Ex:
var imagePaths = [...];
var filterImagePaths = imagePaths.filter(function(imagePath){
//return only those imagepath which fulfill the criteria
return imagePath.includes('index');
});