4

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

3 Answers 3

13

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).

Sign up to request clarification or add additional context in comments.

Comments

1

'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')) {
 ???
}

Comments

1

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');

});

2 Comments

No. The OP may use .some but i dont know how filtering relates to the question?
Filter will create a new array which satisfies the condition i.e., includes a specific word.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.