2

I want to get the largest object in an array of objects, the code I'm using works fine, but I wonder if there is a better way of doing the same. This is the code I'm using.

data=[
    {group: "a", A: 65, N: 20}, 
    {group: "b", R: 52}, 
    {group: "c", N: 20, A: 2, R: 2},
    {group: "d", R: 15, N: 12},
]

len = []
for (var i in data){
    len.push(Object.keys(data[i]).length)
}

for (var i in data){
    if (Object.keys(data[i]).length==Math.max.apply(null, len)){
      subgroups = Object.keys(data[i]).slice(1).sort();
    }
}

console.log(subgroups);

3
  • is your definition of "largest" here the object which has the most properties, or the largest sum of numeric values? Commented Jun 2, 2020 at 14:14
  • what result are you really expecting? the maximum number of keys on an element, the position in the table of this one, something else? Commented Jun 2, 2020 at 14:18
  • No need for 2nd for loop. Just keep track of max value and key in the 1st for loop. Commented Jun 2, 2020 at 14:19

4 Answers 4

4

I think one loop is sufficient to do this.

var data=[
{group: "a", A: 65, N: 20}, 
{group: "b", R: 52}, 
{group: "c", N: 20, A: 2, R: 2},
{group: "d", R: 15, N: 12},
],

max = Object.keys(data[0]).length,
largestObj = data[0];


data.forEach(i=>{
  if(Object.keys(i).length> max){
    max = Object.keys(i).length;
    largestObj = i;
  }
});

console.log(max);
console.log(largestObj);

Sign up to request clarification or add additional context in comments.

2 Comments

I'm only getting the length of the object , no the object
No need to keep the whole object. We can simply keep the key of the object.
2

An example using Array.prototype.reduce

const [biggestObject] = data.reduce(
  ([acc, length], entry) => {
    const len = Object.keys(entry).length;
    return length > len ? [acc, length] : [entry, len];
  },
  [{}, 0]
);

Comments

1

To sort the whole array seems stupid, one loop is enough using reduce function

const { element } = data.reduce((agg, element) => {
  const length = Object.keys(v).length
  if (length > agg.length) {
    return { element, length }
  } 
  return agg
}, { element: null, length: 0 })

Comments

0

You can just sort the array using the criteria you used for filling the len array.

data.sort((x, y) => {
  return Object.keys(y).length - Object.keys(x).length
});

Result:

0: {group: "c", N: 20, A: 2, R: 2}
1: {group: "a", A: 65, N: 20}
2: {group: "d", R: 15, N: 12}
3: {group: "b", R: 52}

1 Comment

I dont like this approach as it has not good perfomance, unnecesserily sorting all the elements but we need just the highest

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.