Table of Contents
Do you want to find a record from an array of records using an identifier or a unique field? Do you want to filter out records matching a certain condition? We will explore all of them in this tutorial.
Consider the following array of employees:
1const employees = [2 {3 id: 1,4 first_name: "Jonas",5 last_name: "Baudasso",7 gender: "Male",8 department: "Support",9 },10 {11 id: 2,12 first_name: "Delcina",13 last_name: "Baldelli",15 gender: "Female",16 department: "Engineering",17 },18 {19 id: 3,20 first_name: "Charlotta",21 last_name: "Sodor",23 gender: "Female",24 department: "Human Resources",25 },26 {27 id: 4,28 first_name: "Scarface",29 last_name: "Sandercock",31 gender: "Male",32 department: "Support",33 },34 {35 id: 5,36 first_name: "Rob",37 last_name: "Beurich",39 gender: "Male",40 department: "Engineering",41 },42]
We will use the above list in our examples.
Finding the index of the object
We can use the findIndex method to get the index of the first matching record.
1const index = employees.findIndex(employee => {2 // Function gets called for each employee until the function returns true3 if (employee.id === 3) {4 return true5 }6 return false7})89console.log(index) // 👉 21011const employee = employees[index]1213console.log(employee?.first_name) //👉 Charlotta
We can simplify the findIndex
function callback to a single line:
1const index = employees.findIndex(employee => employee.id === 3)
If we pass an id that does not exist, the findIndex
function will return -1.
Finding the object directly
We can use the find method to get the object directly without finding the index explicitly.
1const employee = employees.find(employee => employee.id === 3)23console.log(employee?.first_name) //👉 Charlotta
If the employee is not found, the find method will return undefined
.
Finding using a unique key
It is not necessary that we always need to use an id to find the object. We can use other unique fields like email as well:
1const employee = employees.find(3)4console.log(employee?.first_name) // 👉 Rob
If you check for a non-unique in the condition, then it will return the first matching record.
Finding all the records which match the condition
If you want to filter all the records matching a certain condition, then you can use the filter method as shown below:
1const engineers = employees.filter(2 employee => employee.department === "Engineering"3)4console.log(engineers.length) // 👉 2
The filter function returns an array of objects with matching records. If there are no matching records, then it returns an empty array.
Do follow me on twitter where I post developer insights more often!
Leave a Comment