Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
Time complexity of filter with a nested loop

I'm fairly new to Big O and I am not sure what the time complexity of the following code will be:

const items = [
  {type: 'phone', name: 'iPhone', color: 'gold'},
  {type: 'phone', name: 'Samsung', color: 'gold'},
  {type: 'laptop', name: 'Chromebook', color: 'gray'},
  {type: 'tv', name: 'LG', color: 'gray'},
  {type: 'gooo', name: 'LG', color: 'silver'},
  {type: 'phone', name: 'Nokia', color: 'gold'}
];

items.filter(item => {
    for(let i=0; i < Object.keys(item).length; i++) {
        console.log('item is', Object.keys(item)[i])
    }
})

Can we say this is O(i + c) where i is items and c is the constant console.log? Or do we need to say something like O(i * j + c) where j is the individual item i.e. {type: 'phone', name: 'iPhone', color: 'gold'}

Can someone please help me out... thank you in advance!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The items.filter(() => { ... }) is a loop => O(n).

You have a for loop inside of it looping over the object keys => O(m * n).

The Object.keys() is O(m) in V8 and you have it twice in the for loop (in the condition so it's called in every iteration and in the loop body) so it's => O(m ^ 2 * n) (where m is the number of keys).

Also, you can use

for (let key in item) {
  // and do whatever you want with the key
}

instead of using Object.keys.

about 4 years ago · Juan Pablo Isaza Report

0

Let me change your code a bit:

items.filter(item => Object.keys(item).forEach(key => console.log("item is", key)));

The lambda is executed for every item in items. The lambda iterates over every key in an item and prints it. The time complexity is therefore O(n*m) for n = number of items and m = number of keys per item. If the number of keys per item is fixed and relatively small, you can assume O(n). The big O notation is just an rough estimate about the runtime, constant factors aren't that interesting.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!