Home > front end >  Find Object in an array that has the highest number of keys
Find Object in an array that has the highest number of keys

Time:02-17

I have a sample Array of objects like this

let items = [
    {
        a: '',
        b: 2,
        c: 3
    },
    {
        a: '',
        b: '',
        c: 5,
        d: 10
    },
    {
        a: '',
        b: '',
        c: 6,
    }
]

I want to find the first object that has the highest number of keys.

Clearly from the above, the second object has the highest number of keys.

How can I achieve this?

Thank you.

CodePudding user response:

Something like this will work:

let highestLength = 0;
let highestItem = 0;
for (let i = 0; i < items.length; i  ) {
  let objLength = Object.keys(items[i]).length;
  if (objLength > highestLength) {
    highestLength = objLength;
    highestItem = i;
  }
}

Then highestItem will hold the index of the first element with the highest number of keys.

  • Related