admin管理员组

文章数量:1336631

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";
Share Improve this question edited Apr 22, 2020 at 16:09 the Tin Man 161k44 gold badges221 silver badges306 bronze badges asked Apr 21, 2020 at 19:26 user10353169user10353169 3
  • You need to use a loop to pare values. When the first time you get "equal" - exit the loop. If you get all the way through - no matches. Or, if you are allowed, use includes – PM 77-1 Commented Apr 21, 2020 at 19:29
  • Does this answer your question? How do I check if an array includes a value in JavaScript? – Abhishek Duppati Commented Apr 21, 2020 at 20:23
  • Wele to SO! Please see "How to Ask", "Stack Overflow question checklist" and "MCVE" and all their linked pages. Your question is poorly asked. We expect to see evidence of your effort to solve the problem. You gave us a requirement and two variable assignments but nothing showing what you did. Did you research this? If so, why didn't it help? Did you try writing code? If so, why didn't it work? Without that sort of information it looks like you didn't try. – the Tin Man Commented Apr 22, 2020 at 16:11
Add a ment  | 

5 Answers 5

Reset to default 3

You can use the every() method:

let items = [2, 5,9];
let x =  items.every((item)=>{ return item!=0; });
console.log(x);

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);

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 mon 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 remend 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]);
    };
};

本文标签: javascriptHow to test that all values in an array are not equal to a specific valueStack Overflow