Niranjan Godbole Niranjan Godbole - 21 days ago 6
Javascript Question

How to check if all the values in jquery array are equal to one specified string?

Hi I am developing MVC4 application with jquery. I have the following array in my code. This compares if all the elements in array are equal or not. If the array is equal it returns true ot it returns false.
This is my code.

var list = new Array();
$('input[id=Status]').each(function (i, item) {
list.push($(item).val().trim());
});
var statusCheck=!!list.reduce(function(a, b){ return (a === b) ? a : NaN; });
if(statusCheck==true)
{
fun_toastr_notify('success', 'Please verify the documents');
e.preventDefault();
}

I expect the result as below. I want to return true only when all the elemets in the array are equal to "Not Verified".
var list = ["Not Verified", "Not Verified", "Not Verified"] => result: "true"
var list = ["Verified", "Verified", "Verified"] => result: "false"
var list = ["Not Verified", "Verified"] => result: "false"


However i want to return true only if all the elements are equal and each element should be equal to particular string such as "Not Verified". I want to make comparison on particular string. For example if all the list elements are equal to Verified it returns true but i want this to happen only when all the elements are equal to particular string "Not verified". I tried as below.

var statusCheck=!!list.reduce(function(a, b){ return (a.val=='Not Verified' === b.val=='Not Verified') ? a : NaN; });


Above line of code returns true when the elements of list are "verified".

Can someone tell me some valuable suggestions on this. Thank you for your time.

Answer

It seems to me you need to use Array.prototype.every:

["Not Verified", "Not Verified", "Not Verified"].every(function (value) { return value === "Not Verified"}); // true
["Verified", "Verified", "Verified"].every(function (value) { return value === "Not Verified"}); // false
["Not Verified", "Verified"].every(function (value) { return value === "Not Verified"}); // false

Please check this documentation