Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Check if all elements of an array are the same as a variable, or none of them are

I have a javascript variable that is an array of arrays. Then I have a variable below it. Like this:

var cars = [
    ["ford mustang",1955,"red"],
    ["dodge dart",1963,"green"],
    ["pontiac",2002,"green"],
]

var colour = "blue";

Now I need to check for if either the third values of each array are all the same as the variable, colour, or they are all different. If one of those conditions are true, I want to execute some other code. So in the above example, the condition would be true because none of the values are "blue". It would also be true if they were all "blue".

Hopefully I've made myself clear.

like image 434
eshellborn Avatar asked Dec 02 '22 21:12

eshellborn


2 Answers

There are two functions in JavaScript just for that:

allCarsAreRed = cars.every(function(car) { return car[2] == 'red' })
atLeastOneCarIsRed = cars.some(function(car) { return car[2] == 'red' })
noRedCars = cars.every(function(car) { return car[2] != 'red' })
  • some

  • every

like image 197
georg Avatar answered Jan 17 '23 02:01

georg


var colour = 'blue'
var all = true;
var none = true;
for (var i = 0; i < cars.length; i++) {
   if (cars[i][2] !== colour) {
      all = false;
   } else  {
      none = false;
   }

}
like image 37
DavidC Avatar answered Jan 17 '23 03:01

DavidC