I have an if statement inside two nested for loops in my javascript code as below.
The problem is that the execution slows down when I have to compare thousands of objects in the array as the loop iterates through the entire array just to check for a single matching value.
When the key in data object matches with the id of an object from the arr array it adds a username key to the objects in arr array.
Please run the following code and see the output :
var data = { 1: 'John',
2: 'Josehp',
8: 'Marley',
3: 'George',
4: 'Stella',
5: 'Stanley',
123: 'Juhi'
}
var arr = [ { id: '1'
},
{ id: '2'
},
{ id: '10'
},
{ id: '3'
},
{ id: '4'
},
{ id: '13'
},
{ id: '5'
}
];
var x;
for (x in data) {
for (i = 0; i < arr.length; i++) {
if (arr[i].id == x) {
arr[i].username = data[x];
}
}
}
console.log(arr)
How can I optimise this code to avoid nested loops or simply improve the performance ?
if loop? Do you mean if statement?