1
var array = [
{'a':1,'b':2},
{'a':1,'b':3},
{'a':1,'b':0},
]

I want to return array that its' property b is equal to 2

2 Answers 2

5

You can use Array.prototype.filter like this

var result = array.filter(function(currentObject) {
    return currentObject.b === 2;
});

console.log(result);
# [ { a: 1, b: 2 } ]

You can also do this with plain for loop, like this

var result = [];
for (var i = 0; i < array.length; i += 1) {
    if (array[i].b === 2) {
        result.push(array[i]);
    }
}

console.log(result);
# [ { a: 1, b: 2 } ]
Sign up to request clarification or add additional context in comments.

2 Comments

how can I use that 'return'?
@user3522457 filter will gather all the items for which the function returns true and all those items will be available in result, like I have shown in my example.
0
var result;
for (var i = 0; i < array.length; i += 1) {

     if (array[i].b === 2) {
         result = array[i];
         break;
     }

}

console.log(result);

use a break to make some difference.

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.