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.

theduck
  • 2,589
  • 13
  • 17
  • 23
  • 1
    what is the result, you are expecting? – Nina Scholz Jan 04 '20 at 16:34
  • [Array.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)? – Dan O Jan 04 '20 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 –  Jan 04 '20 at 16:37
  • oh. then you want [Array.every](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every). – Dan O Jan 04 '20 at 16:38

3 Answers3

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)));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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

array.forEach(item =>
  console.log(["brad", "miranda", "john"].includes(item) ? "success" : "fail")
);
Siva K V
  • 10,561
  • 2
  • 16
  • 29
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)));