Reputation: 607
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
Upvotes: 4
Views: 30779
Reputation: 2753
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');
});
Upvotes: 1
Reputation: 10396
'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')) {
???
}
Upvotes: 1
Reputation: 1075925
You 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).
Upvotes: 13