How can I check an array to test that all the data in the array are not equal to a variable's value:
var values = ["1", "2", "3"];
var value = "0";
How can I check an array to test that all the data in the array are not equal to a variable's value:
var values = ["1", "2", "3"];
var value = "0";
You can use .some()
.
From the documentation:
The
some()
method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
Try this:
const values = ["1", "2", "3"];
const value = "0";
const hasValue = values.some(e => e === value);
console.log(hasValue);
You can use the every()
method:
let items = [2, 5,9];
let x = items.every((item)=>{ return item!=0; });
console.log(x);
var values = ["1", "2", "3"];
var value = "0"
const isExist = !!values.find(_value => _value === value);
There are many ways to check whether all the values in an array are not equal to a given value.
Most common methods are .every() and .some()
If don't want to use predefined methods then looping is good option or else first get distinct value in array and then use the index of() to check if index of given value is greater than zero then array all values are nit equal to given value.
This is pretty simple, and there are multiple answers, however, I'd recommend using a for
loop as the simplest way to do this.
I like using these since, as long as you have some knowledge of JavaScript, this code is easy to read, making it versatile. A for
loop would look like this:
var values = ["1", "2", "3"];
var value = "0";
var newArray = [];
for (let i = 0; i < values.length; i++) {
if (values[i] != value) {
newArray.push(values[i]);
};
};