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.
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
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With