2

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);
1
  • 2
    Every implementation will use some form of for-loop. However you don't have to write the 'low level' loop manually. You can use Array.some, for example. Or something from lodash. Commented May 29, 2015 at 1:38

1 Answer 1

3

You can use some like

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

console.log(flag); // true
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.