How to avoid for loop inside for loop in javascript
The complexity of having nested loops in your case is O(n * m) - n the length of orderArr
, and m the length of myArr
.
This solution complexity is O(n + m) because we're creating the dictionary object using Array#reduce with complexity of O(m), and then filtering the orderArray
with a complexity of O(n).
Note1: For small arrays, this shouldn't really matter. So unless you've got a few thousands in both array, you can stay with the nested loops.
Note2: This code assumes that there are no duplicates in myArr
. If there are duplicates, the result will differ from that of the nested loops.
var myArr = ['a', 'b', 'c', 'd', 'e'];
var orderArr = ['e', 'c'];
var myArrDict = myArr.reduce(function(r, s) {
r[s] = true;
return r;
}, Object.create(null));
var reArr = orderArr.filter(function(s) {
return this[s];
}, myArrDict);
console.log(reArr);
I wouldn't necessarily say that using loops inside loops is a bad practice -- in fact Ori Drori beat me to stating that the efficiency of such a practice might simply depend on the size of the data set.
For example, there are many implementations of sorting algorithms and you'll often find loops within loops. However the details of the implementation impact the performance as the data sizes change.
My own personal experience is that when I see nested loops I immediately ask myself if the operation it's performing needs to be optimized with a different algorithm. More often than not in JavaScript (browser) applications the answer is "no" because data sizes are rarely big enough to make an impactful difference.