doe
doe

Reputation: 455

Getting an object with maximum array length for a given property

I'm trying to get an object having a property with the longest array length from an array objects.

[ {a:[...],...}, {a:[...],...}, ... } ]

Lodash has maxBy to get the object with property having max value but I want to check the length of the property's array. My object also has a getCount() function but that doesn't work either so I guess it's because lodash can only check property's numeric value. Can lodash's maxBy use the length of an array as the condition somehow?

Upvotes: 1

Views: 1687

Answers (3)

slash_rick_dot
slash_rick_dot

Reputation: 923

Array.reduce() works well for this type of thing. Something like:

const arr = [{a: [1]}, {a: [1,2]}, {a: [1,2,3]}];

const result = arr.reduce( (e1, e2) => e1.a.length>e2.a.length ? e1: e2 );

console.log( "Element of arr having longest a:", result );

The Array.reduce method calls the function you give it with arguments for the 'result so far' (e1) and the current element (e2). In this case your function simply returns the one with the longest 'a'.

Nicest thing is there's no library dependency.

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

You can simply use Math.max and map

let arr = [{a: [1]}, {a: [1,2]}, {a: [1,2,3]}];

let op = Math.max(...arr.map(({a})=>a.length))

console.log(op)

Upvotes: 1

Turtlefight
Turtlefight

Reputation: 10800

You can use _.maxBy:

let arr = [{a: [1]}, {a: [1,2]}, {a: [1,2,3]}];

// with a lambda
console.log(_.maxBy(arr, obj => obj.a.length));

// with `_.property` iteratee shorthand
console.log(_.maxBy(arr, 'a.length'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Upvotes: 1

Related Questions