r_cahill
r_cahill

Reputation: 607

Javascript 'if' statement using .includes()

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

Answers (3)

Anurag Singh Bisht
Anurag Singh Bisht

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

Alberto Trindade Tavares
Alberto Trindade Tavares

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

T.J. Crowder
T.J. Crowder

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

Related Questions