Categories
JavaScript Answers

How to Find the Index of an Object in an Array From a Given Object?

Spread the love

Sometimes, we want to find the index of an object in an array from a given object.

In this article, we’ll look at how to find the index of an object in an array from a given object.

Find the Index of an Object in an Array From a Given Object

To find the index of an object in an array from a given object, we can use the JavaScript array’s and Object.entries methods and also the JavaScript array’s every method.

JavaScript array’s entries method returns an array of arrayt with the index and entry of the array.

The Object.entries method returns an array of array of key-value pairs of an object.

And the JavaScript array’s every method returns whether every entry of an array matches a given condition.

For instance, we can write:

const indexOf = (arr, obj) => {
  for (const [index, aObj] of arr.entries()) {
    const allEqual = Object
      .entries(aObj)
      .every(([key, val]) => {
        return obj[key] === val
      })
    if (allEqual) {
      return index;
    }
  }
  return -1;
}

const obj = {
  x: 1,
  y: 2
};
const arr = [{
    x: 1,
    y: 2
  },
  {
    x: 3,
    y: 4
  }
]
const index = indexOf(arr, obj)
console.log(index)

We create the indexOf function that takes an arr array and obj object.

In it, we have a for-of loop to loop through each entry of the arr array.

Then we get the key-value pairs of each entry with the Object.entries method.

Next, we call every with the key and val key-value pair and check if they obj[key] is the same as the val value.

And we assign that value to allEqual .

If that’s true , then we return the index ,

If we loop through all the entries and found nothing, then we return -1.

Next, we call indexOf with arr and obj and get that index is 0.

Conclusion

To find the index of an object in an array from a given object, we can use the JavaScript array’s and Object.entries methods and also the JavaScript array’s every method.

JavaScript array’s entries method returns an array of arrayt with the index and entry of the array.

The Object.entries method returns an array of array of key-value pairs of an object.

And the JavaScript array’s every method returns whether every entry of an array matches a given condition.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *