Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return object in an array with the most props

Say I have an array of objects like this:

const arr = [
   { a: 1, b: 2, c: 3, d: 4 },
   { a: 1 },
   { a: 1, b: 2, c: 3 },
   { a: 1, b: 2 }
];

How can I return the object with the most properties/keys? Preferably using in an efficient and terse manner using higher order functions.

like image 268
stickleBrick Avatar asked Feb 25 '26 12:02

stickleBrick


2 Answers

You could assign to a single object.

const 
    array = [{ a: 1, b: 2, c: 3, d: 4 }, { a: 1 }, { a: 1, b: 2, c: 3 }, { a: 1, b: 2 }],
    object = Object.assign({}, ...array);

console.log(object);

If you have different values, you could reduce the array.

const 
    array = [{ a: 1, b: 2, c: 3, d: 4 }, { a: 1 }, { a: 1, b: 2, c: 3 }, { a: 1, b: 2 }],
    object = array.reduce((a, b) => Object.keys(a).length > Object.keys(b).length
        ? a
        : b
    );

console.log(object);
like image 90
Nina Scholz Avatar answered Feb 27 '26 00:02

Nina Scholz


You can get the number of keys from an object by calling Object.keys(obj) and then checking it's length property. With that, you could reduce the array by checking each pair of objects and return the one with the most keys as a one liner:

const biggestObject = 
    arr.reduce((a, b) => Object.keys(a).length > Object.keys(b).length ? a : b);
like image 26
Mureinik Avatar answered Feb 27 '26 02:02

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!