1

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

4 Answers 4

2

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)

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

4 Comments

I just want to get the min keys, not the item itself
well that's even simpler. just calculate Object.keys(result).length if you don't want to change the code
I just want to get 1. not the object
Then use the other solution
1

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.

Comments

0

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

Comments

0

Here is my solution :

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

1 Comment

I dont want to get the name, just 1

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.