Javascript: How to find an object in an Array of objects

In this article, we will learn how to search and find an object in an array of objects based on particular criteria. First, we will discuss different ways in which we can find an object in an array and then move on to the different criteria through which we can search for the object.

Let’s consider an example of an array of car objects with properties of id, brand, model, price, and release_date with id having the unique value for every object.

Filtering Array of objects in React...
Filtering Array of objects in React JS
car_list
List of cars, source: pinterest.com
const carList = [{ id:13, brand: "BMW", model: "X5", price:"$23000", release_date:"2015-10-12"},

                 { id:9, brand: "Audi", model: "S3", price:"$35000", release_date:"2013-08-23"},

                 { id:11, brand: "Bugatti", model: "Veyron", price:"$500000", release_date:"2006-02-10"},
                 
                 { id:7, brand: "VW", model: "Polo", price:"$8000", release_date:"2018-05-03"},
                
                 { id:4, brand: "Fiat", model: "Punto", price:"$6000", release_date:"2017-01-25"}]

There are two approaches to find the required object, they are as follows:

  1. Finding index of search object using Array.findIndex()
  2. Searching the object directly using Array.find()

Method 1: Array.findIndex() to find the search index

The first approach would be to find the array index of the search object using Array.findIndex(). Once the search index is found, we can access the search object by “array[index]” and then perform any required operations on the object that is found. This method is useful when we need to update the search object reference of the array.

In the below example, we find the index of the object with model value as “X5” and print the price and brand through the “carList[searchIndex]” object reference. Read more about Array.findIndex() from developer.mozilla.org/Array/findIndex.

// Finding index of the car with modal "X5" 
const searchIndex = carList.findIndex((car) => car.model=="X5");

console.log(`Model X5 is present in brand ${carList[searchIndex].brand}`);
//"Model X5 is present in brand BMW"

console.log(`The price of model X5 is ${carList[searchIndex].price}`);
//"The price of model X5 is $23000"

Method 2: Array.find() to find the search object

Another approach would be to find the search object itself by using Array.find() and assign it to a variable. Now all the search object details can be accessed from this variable. This approach is more suitable if we want to perform operations on search objects independently from the array.

In the below example, we find the object entry with model value as “X5” from the array using Array.find() and print its brand and price values. Read more about Array.find() from developer.mozilla.org/Array/find.

// Finding car object with modal "X5" 
const searchObject= carList.find((car) => car.model=="X5");

console.log(`Model X5 is present in brand ${searchObject.brand}`);
//"Model X5 is present in brand BMW"

console.log(`The price of model X5 is ${searchObject.price}`);
//"The price of model X5 is $23000"

We need criteria to search the object in the array of objects, here we will discuss 3 types of search that are as follows:

  1. Search object by unique id / Property value
  2. Search object with Min & Max property value
  3. Search object with Latest or oldest date

Find object by Unique id / Property value

The most common approach is to match the search object by unique id or property value, however, it would fail if two or more items have the same value. Simple “==” operator coupled with Array.find() will achieve a successful search operation.

In the below example, carList has a property of “id” which is unique to every object in the array. We find the car object with id = 11 from the array and print the details of the object found.

const searchId = 11;

// Finding car object with id 11
const searchObject = carList.find((car) => car.id == searchId);

const {brand, model, price} = searchObject;

console.log(`Car with id ${searchId} is ${brand} ${model}`);
//"Car with id 11 is Bugatti Veyron"

console.log(`${brand} ${model} is priced at ${price}`);
//"Bugatti Veyron is priced at $500000"

Find object with Min & Max value in array

We can find objects with minimum and maximum values in an array of objects in 3 steps:

  1. Create array of property values using Array.map((item) => item.property)
  2. Find min / max value from the array using Math.max.apply(null, array) or Math.min.apply(null, array)
  3. Find the object with max/ min value using Array.find((item) => item.property == max_value/min_Value)

In the below example, we are finding the most expensive and cheapest car object from carList array.

// Creating array with all prices in number
const prices = carList.map((car) => Number(car.price.replace("$", "")))

// Calculate higest and lowest price value
const highestPrice = "$" + Math.max.apply(null, prices);
const lowestPrice = "$" + Math.min.apply(null, prices);

// Matching values to find the expensive and cheap car
const expensiveCar = carList.find((car) => car.price == highestPrice)
const cheapCar = carList.find((car) => car.price == lowestPrice)

console.log(`Most expensive Car is ${expensiveCar.brand} ${expensiveCar.model} at ${highestPrice}`)
// "Most expensive Car is Bugatti Veyron at $500000"

console.log(`Cheapest Car is ${cheapCar.brand} ${cheapCar.model} at ${lowestPrice}`)
// "Cheapest Car is Fiat Punto at $6000"

Based on Latest or Oldest Date

We need to follow 4 steps to find an object with a min/max date from the array of objects:

  1. Make sure the date field of objects are in YYYY-MM-DD format.
  2. Define callback function for max value which returns Date.parse(car1.release_date) < (Date.parse(car2.release_date) ? a : b
  3. Callback function for min value with Date.parse(car1.release_date) > (Date.parse(car2.release_date) ? a : b
  4. Apply Array.reduce() with the callback function and assign the return value to a variable

In the below example, we find cars with the oldest and latest release date from carList array based on the “release_date” property value.

// "Get car with oldest release date"
const oldestCar = carList.reduce((car1, car2) => {
  return (Date.parse(car1.release_date)) < (Date.parse(car2.release_date)) ? a : b;
});

console.log(`The Oldest Car is ${oldestCar.brand} ${oldestCar.model} at ${oldestCar.release_date}`)
// "The Oldest Car is Bugatti Veyron at 2006-02-10"

// "Get car with latest release date"
const latestCar = carList.reduce((car1, car2) => {
  return (Date.parse(car1.release_date)) > (Date.parse(car2.release_date)) ? a : b;
});

console.log(`The Latest Car is ${latestCar.brand} ${latestCar.model} at ${latestCar.release_date}`)
//"The Latest Car is VW Polo at 2018-05-03"