Javascript has many frameworks in which underscore.js is one of them. It has provided many functions in which _.where() is a function used to find elements based on a specific condition.
This method will display the elements based on whether they passed the condition or not. For suppose if we passed a condition that how many of the people from the provided array have salaries equal to 15000, then the method _.where() scrutinizes every element whether it passed the condition or not. If any of the elements passed the condition, then that particular element will be displayed as the output.
syntax
_.where( list, testCondition);
It accepts an array to scrutinize and a scrutinizing condition to evaluate the elements. The elements that have passed the condition will be displayed as the output.
Example-1
In the following example, a condition is passed regarding ages and output is displayed based on the condition.
<html>
<body>
<script
src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
<script>
var people = [
{"name": "Dhoni", "age": 38},
{"name": "kohli", "age": 22},
{"name": "Rohit", "age": 28},
{"name": "dhawan", "age": 28}
]
document.write(JSON.stringify(_.where(people, {age: 28})));
</script>
</body>
</html>Output
[{"name":"akansha","age":28},{"name":"preeti","age":28}]Example-2
In the following example, the array "students" is scrutinized by passing a condition regarding their id's and results are displayed as shown in the output.
<html>
<body>
<script
src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
<script>
var students = [
{"name": "Ravi", "id": 45},
{"name": "Surya", "id": 45},
{"name": "Chandra", "id": 47},
{"name": "guru", "id": 40}
]
document.write(JSON.stringify(_.where(students, {id:45})));
</script>
</body>
</html>Output
[{"name":"Ravi","id":45},{"name":"Surya","id":45}]