skip to Main Content

How do I achieve this with a single if ? In other words, if(fruit != "apple" || fruit != "orange"){ is not producing the expected result?

fruits.forEach(function(fruit){
  if(fruit != "apple"){ // < ----I want to use a compound OR, or compare multiple strings.
    if(fruit != "orange"){ // <---------I want this nested if gone.
      console.log(fruit + " is not apple or orange [two]");
    }
  }
});
const fruits = ["apple","orange","banana","cherry"];

fruits.forEach(function(fruit){
  if(fruit != "apple"){
    console.log(fruit + " is not apple");
  }
});

fruits.forEach(function(fruit){ //<------- this is what I'm having problems with
  if(fruit != "apple" || fruit != "orange"){
    console.log(fruit + " is not apple or orange [one]");
  }
});

fruits.forEach(function(fruit){
  if(fruit != "apple"){
    if(fruit != "orange"){
      console.log(fruit + " is not apple or orange [two]");
    }
  }
});

2

Answers


  1. @Pointy points out that:

    const fruits = ["apple","orange","banana","cherry"];
    
    fruits.forEach(function(fruit){
      if(fruit != "apple"){
        console.log(fruit + " is not apple");
      }
    });
    
    fruits.forEach(function(fruit){ //<------- this is what I'm having problems with
      if(fruit != "apple" && fruit != "orange"){ // notice
        console.log(fruit + " is not apple or orange [one]");
      }
    });
    
    fruits.forEach(function(fruit){
      if(fruit != "apple"){
        if(fruit != "orange"){
          console.log(fruit + " is not apple or orange [two]");
        }
      }
    });
    Login or Signup to reply.
  2. One liners?

    const fruits = ['apple', 'orange', 'banana', 'cherry'];
    fruits
      .filter(f => f !== 'apple' && f !== 'orange')
      .forEach(f => console.log(`${f} is nor apple nor orange`));
    
    // alternatively
    fruits
      .filter(f => !['apple', 'orange'].includes(f))
      .forEach(f => console.log(`${f} is nor apple nor orange`));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search