eshellborn eshellborn - 1 year ago 116
Javascript Question

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"],

var colour = "blue";

Now I need to check for if either the third values of each array are all the same as the variable,
, 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.

Answer Source
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;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download