I need to fill an array with the properties from each continent for each year.
Is there a better and more optimal way of iterating through the following object without using nested for-loops which have a time complexity of O(n2) if I am not mistaken ?
const data = {
2000: {
Europa: {
prop1: "1",
prop2: "2",
},
Asia: {
prop1: "1",
prop2: "2",
},
},
2001: {
Europa: {
prop1: "1",
prop2: "2",
},
Asia: {
prop1: "1",
prop2: "2",
},
},
};
As a junior dev, I tend to write the solution like this :
for (const year of Object.keys(data)) {
const traces = [];
for (const continent in data[year]) {
traces.push(data[year][continent]);
}
console.log("traces", traces);
}
I understand that if there are only a few hundreds data points, even this code is fast, but what if we have hundred of thousands of data points in the above format ?
Also, searching on Google for "is recursion faster than nested for-loops" generally returns a negative answer and it seems that from a time complexity perspective it’s the same.
2
Answers
There is no way of avoiding visiting every object, if you want to extract every object.
Note that you can concisely extract an array of arrays of objects, and then do something with it afterwards, like this:
The time complexity of your code is actually O(nm), where n is the number of years and m is the number of continents. Since you need to iterate through all the years and all the continents for each year to fill the array with the properties from each continent for each year, it’s not possible to achieve a better time complexity than O(nm) for this specific task.
However, you can make your code more readable and concise by using
Object.values()
andArray.prototype.map()
instead of nested for-loops:This code has the same time complexity as your original code but is more readable and easier to understand.