I have an array of objects, arr1, where each object has multiple properties. I also have a map, map2, where the keys are strings and the values can be of any type. My goal is to find the matching keys between arr1 and map2.
Here is an example of the code I currently have:
// Assume arr1 is an array of objects, each object having multiple properties
var arr1 = [{Alice: 1, Bob: 2}, {Alice: 2,Charlie: 3, David: 4}, {Charlie: 4,Eve: 5, Frank: 6}];
// Assume map2 is a map, with keys as strings and values of any type
var map2= new Map();
map2.set("Alice", 1);
map2.set("David", 2);
map2.set("Eve", 3);
// Original nested for loop
for (var i = 0; i < arr1.length; i++) {
for (var [key, value] of map2) {
for (var name in arr1[i]) {
if (arr1[i][name] == key) {
arr1[i][name] = map2.get(key)
}
}
}
}
// Optimized nested for loop
for (var i = 0; i < arr1.length; i++) {
for (var name in arr1[i]) {
if (map2.has(name)) {
arr1[i][name] = map2.get(name)
}
}
}
The code works as expected, but I wonder if any further optimizations can be done to improve its efficiency. Currently, I iterate over arr1 and check every property of every object against the key in map2. If a match is found, the matching key is recorded. However, the large amount of arr1 data and the number of map keys are inefficient, and I do not know if there is a better way.
Is there a more efficient approach to achieve the same result? Any suggestions or insights would be greatly appreciated. Thank you!
3
Answers
The iterating map keys seems more efficient since the number of keys is potentially smaller that in the array items. But you can have some optimization here: convert the map’s keys to an array and use it when iterating the array items:
But there’s another way to improve the performance: generate a JS code to update the array:
And benchmark the approaches.
Here we add additional array item props and map entries(John Sam Peter Maria Alex Trevor Victory Samuel Carl Steve Bill Joe) and multiply array items by 500.
Seems the iterating map keys with caching has the same speed as iterating the array keys if the number of keys are the same.
Anyway you should iterate a smaller key array (if the map contains less entries – iterate it, otherwise iterate the array items’ keys).
Without caching the speed is awfully 900x slower since every array item you fetch a new map iterator which is expensive plus using a iterator is 6.2x slower in chrome than using an array:
Efficiency mostly is about finding a good balance in between performance and readability/maintainability.
Thus, the next provided example code targets readability and waits for being performance tested by Alexander’s testing tool.
The code can be read almost literally …
… and could be directly transformed into …
… in case one makes use of
for...of
(iterable) andfor...in
(object)This is improvised Answers for your question.