javascript
Array.find() - get the very first element satisfy a condition Javascript
Array.find() in javascript can be used to get the very first element that satisfies one or multiple conditions enclosed in a function.
const numbers = [50, 60, 70, 80];
const element = numbers.find(num => num > 50);
console.log(element);
// -> 60
In the code snippet, We have an array named numbers that contains multiple integer values. We are trying to find the array element that has a value greater than 50. We are using the .find() method of javascript Array and applying the condition inside the function.
Live Demo
const names = ["Rick Grimes", "John Snow", "Carol", "Misshone"];
//Using ES syntax
const name_snow = names.find(name => name.indexOf("Snow") != -1);
console.log(name_snow);
// -> John Snow
// Using function
const name_snow_2 = names.find(function(name) {
return name.indexOf("rol") != -1
});
console.log(name_snow_2);
// -> Carol
In this code example, we are getting the very first item that has a value in an array value. We have created an array named names that contains multiple values. Using names.find() method we are getting the array item that contains a value on condition-based.
const subjects = [
{"name": "Math", "score": 85},
{ "name": "Physics", "score": 90 },
{ "name": "Chemistry", "score": 95 }
];
const subject = subjects.find(sub => sub.score > 90);
console.log(subject);
// -> { "name": "Chemistry", "score": 95 }
Here, we are getting an object whose property has a specific value. We have created an object subjects that contains multiple objects with keys name and score. We are getting the very first object that has score value greater than 90 using subjects.find().
Was this helpful?
Similar Posts
- Lodash - get the first element from an array
- Find the nth largest element in a sorted array
- Javascript to find which DOM element has the focus
- Lodash - Get index of array item based on some condition
- Test every item of array against some condition in javascript
- Find the minimum value from an array javascript
- Find the maximum value from an array using Javascript