简体   繁体   中英

How to find if an array element contains a specific value in JavaScript/jQuery?

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

You can use some like

var flag = myarray.some(function(obj){
  return obj.group === 2;
});

console.log(flag); // true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM