Reputation: 31
Is possible to check if there is at least an array element that contains a specific value, without using a for loop? Or I am using the most efficient way?
I am working with a large number of data (1000+).
Sample array:
var myarray = [
{id: 0, content: "demo0", group: 1},
{id: 1, content: "demo1", group: 2},
{id: 2, content: "demo2", group: 2},
{id: 2, content: "demo3", group: 4},
]
I want to check if it contain elements with "group == 2". My code:
var arrayLength = myarray.length;
var flag = false;
for (var i = 0; i < arrayLength; i++) {
if (myarray[i]["group"] == 2) {
flag = true;
break;
}
}
alert(flag);
Upvotes: 2
Views: 735
Reputation: 2780
You can use some like
var flag = myarray.some(function(obj){
return obj.group === 2;
});
console.log(flag); // true
Upvotes: 3