1

So I have an array ["miranda","brad","johnny"] and I want to check if in the array the values are either equal to miranda or to john or even brad to return true one time and not three times if one or more of the names are present and if not It displays an error if any other value are in this array. Now to make my example clearer here is a snippet that would represent what I'm thinking of:

let array = ["miranda","brad","johnny"]
for(var i = 0; i < array.length;i++){
  if(array[i] == "brad" || array[i] == "miranda" || array[i] == "john"){
  console.log("success")
 } else{ 
 console.log("fail");
 break;
 }
}

Now my goal here is to simplify and shorten this code to be left with a one line condition, I have already tried this technique (Check variable equality against a list of values) with if(["brad","miranda","john"].indexOf(array) > -1) { // .. } but this does not solve my problem. Would you have any idea? Thanks in advance.

4
  • 1
    what is the result, you are expecting? Commented Jan 4, 2020 at 16:34
  • Array.some? Commented Jan 4, 2020 at 16:36
  • To assign the array values of a json file to my javascript file only if the json array does not contain other names Commented Jan 4, 2020 at 16:37
  • oh. then you want Array.every. Commented Jan 4, 2020 at 16:38

3 Answers 3

3

You could use Array#every in combination with Array#includes.

var array = ["miranda", "brad", "johnny"],
    needed = ["brad", "miranda", "john"];
    
console.log(array.every(s => needed.includes(s)));

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

Comments

0

let array = ["miranda","brad","johnny"]

array.forEach(item =>
  console.log(["brad", "miranda", "john"].includes(item) ? "success" : "fail")
);

Comments

0

The answer above covers the solution but you just need to use Array#some instead of Array#every -

var array = ["miranda", "brad", "johnny"],
    needed = ["brad", "miranda", "john"];
    
console.log(array.some(s => needed.includes(s))); 

Comments