return object in an array with the most props

Viewed 44

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.

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);

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);
Related