Olaf Mudj
Olaf Mudj

Reputation: 3

JavaScript if array contains name then dont do it

So I have this piece of code:

if(item.name != "Banana" || "Apple"){
console.log("Good job");
} else{
console.log("Mad");
}

Basically, that part doesn't work != it still goes with those names. Doesn't ignore them.

Upvotes: 0

Views: 44

Answers (2)

BeNdErR
BeNdErR

Reputation: 17927

var fruits = ["Banana", "Apple"];
if( fruits.indexOf(item.name) != -1 ){
    console.log("name is banana or apple")
} else {
    console.log("name is neither banana nor apple")
}

is this what you are looking for?

Anyway

if(item.name != "Banana" || "Apple")

this piece of code will always evaluate "Banana" over "Apple" as the or operator works with the first argument that is not falsy. "Banana" is evaluated as true then the if condition will always be

if (item.name != "Banana")

Upvotes: 4

Gian Marco Toso
Gian Marco Toso

Reputation: 12136

Just to throw another option out there, you can filter an array through the use of higher order functions, in this case the builtin array's filter function:

var withoutApplesAndBanans = myArray.filter( function(item) { 
     return item.name !== 'Apple' && item.name !== 'Banana'; 
} );

You could also build an array of 'forbidden' words, and use that instead of a hard comparison:

var forbiddenWords = ['Apple, 'Banana'];

var withoutApplesAndBanans = myArray.filter( item => forbiddenWords.indexOf(item.name) === -1 ) ;

Upvotes: 0

Related Questions