Reputation: 2036
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.
Upvotes: 0
Views: 834
Reputation: 24638
Start by .sort()
ing in descending order by number of keys. Then return the first element.
let items = [{
a: '',
b: 2,
c: 3
},
{
a: '',
b: '',
c: 5,
d: 10
},
{
a: '',
b: '',
c: 6,
}
];
const mostkeys = items.sort(
(a,b) => Object.keys(b).length - Object.keys(a).length
)[0];
console.log( mostkeys );
If, however, you have more than one having the most keys and you would like to return all, your approach would be slightly different at the last step:
let items = [{
a: '',
b: 2,
c: 3
},
{
a: '',
b: '',
c: 5,
d: 10
},
{
a: '',
b: '',
c: 6,
},
{
c: '',
d: '',
e: 6,
f: 3
}
];
const mostkeys = items.sort(
(a,b) => Object.keys(b).length - Object.keys(a).length
)
.reduce((m, cur, i, a) =>
i === 0 ? [...m,cur] : Object.keys(cur).length < Object.keys(m[0]).length ? m : [...m,cur], []
);
console.log( mostkeys );
Upvotes: 1
Reputation: 557
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.
Upvotes: 2