NEOJPK
NEOJPK

Reputation: 823

Check which array has the highest length inside an object

Im using lodash.js but seems like there isnt a way to do this. I tried myself but im not happy with the result

function checkHighestArrayCountFromObject(object) {
  var counter = 0;
  for (let property in object) {
    if (object.hasOwnProperty(property)) {
      counter = object[property].length > counter ? object[property].length : counter
    }
  }
  return counter
}


var obj = {
  a: [2, 3, 4, 5],
  b: [2, 3, 4],
  c: [2, 3],
  d: [2],
}

console.log(checkHighestArrayCountFromObject(obj)) // => length of (a) should be returned

What im not seeing.

Upvotes: 0

Views: 1261

Answers (5)

If using lodash you can use reduce

_.reduce(obj, (max, n) => n.length > max ? n.length : max, 0);

Upvotes: 0

Shivam
Shivam

Reputation: 3622

const obj = {
  a : [2,3,4,5],
  b : [2,3,4,],
  c : [2,3],
  d : [2],
}

_.chain(obj)
.reduce((max,v,k)=> {
  if(v.length>max.len){
    max.len = v.length;
    max.key=k
  };
  return max
},{len:-1,key:''})
.get('key').value()

Or Simply do a reduce on the obj and get the property key from the result

Upvotes: 0

Barmar
Barmar

Reputation: 781105

If using Lodash you can use _.max:

_.max(Object.values(obj).map(a => a.length))

Upvotes: 1

str
str

Reputation: 44979

Another compact way to write this is to use Math.max:

function checkHighestArrayCountFromObject(object) {
  return Math.max(...Object.values(object).map(o => o.length))
}

Upvotes: 0

janos
janos

Reputation: 124656

You could get the values from the object using Object.values, map them to their length, and finally use reduce to find the maximum value:

Object.values(obj).map(a => a.length).reduce((a, b) => Math.max(a, b))

Upvotes: 2

Related Questions