Home > Blockchain >  Find object with least keys from array (With Snippet)
Find object with least keys from array (With Snippet)

Time:09-30

My code works well. But I tested with data of 1 million entries and it crashes RangeError: Maximum call stack size exceeded

I don't know why... How can I improve my code??

const data = [{
    name: 'John',
    age: 32,
    street: 'str'
  },
  {
    name: 'Maria',
    age: 20
  }, 
  {
    name: 'Elizabeth',
    age: 20,
    foo: 'bar'
  }, 
  {
    name: 'Batman'
  }
]

for (var i=0; i<1000000; i  ) {
  data.push({
    some: 'thing',
    code: 'tango'
  })
}

const minKeys = Math.min(...data.map((el) => Object.keys(el).length));

console.log(minKeys);

The answer here should be the 1 because it has just 1 key, name

CodePudding user response:

I think this should perform well. Lets make some tests

const data = [{
    name: 'John',
    age: 32,
    street: 'str'
  },
  {
    name: 'Maria',
    age: 20
  }, 
  {
    name: 'Elizabeth',
    age: 20,
    foo: 'bar'
  }, 
  {
    name: 'Batman'
  }
];

for (var i=0; i<1000000; i  ) {
  data.push({
    some: 'thing',
    code: 'tango'
  })
}

var min = data.reduce(function(agg, item) {
 if (!agg || Object.keys(item).length < Object.keys(agg).length) {
  agg = item;
 }
 return agg;
})


console.log(min)

CodePudding user response:

Iterate over the objects like this:

const data = [{
    name: 'John',
    age: 32,
    street: 'str'
  },
  {
    name: 'Maria',
    age: 20
  }, 
  {
    name: 'Elizabeth',
    age: 20,
    foo: 'bar'
  }, 
  {
    name: 'Batman'
  }
]

let minKeys = 1e12
for (const obj of data) {
    const keys = Object.keys(obj).length;
    if (keys < minKeys) {
        minKeys = keys;
    }
}

console.log(minKeys);

CodePudding user response:

Here is my solution :

const minKeys = data.reduce(function(prev, curr) {
    return Object.keys(prev).length < Object.keys(prev).length ? prev.name : curr.name;
});

CodePudding user response:

There is a limited number of arguments you could pass to a function, having 1 million entries means that you are passing 1 million arguments to the Math.min() that's why you are getting the error. As for the answer I think IT goldman gave you a decent one.

  • Related