I have solved an algorithm using a for loop, but I have been trying to use a for of loop, to make it easier to read, but i'm not getting the same output when I used a traditional for loop?
const sortByHeight = (a)=>{
const array2 = a.filter(num => {
if (num !== -1){
return num
}
}).sort((a,b) => a-b)
let indexVal = 0;
for ( let num of a){
if(num !== -1 ){
num = array2[indexVal]
indexVal++
}
}
return a;
//for loop does work
// for ( let i=0; i < a.length; i++){
// if(a[i] !== -1 ){
// a[i] = array2[indexVal]
// indexVal++
// }
// }
// return a;
console.log(sortByHeight([-1, 150, 190, 170, -1, -1, 160, 180]));
}
num
is a local variable inside the loop. Assigning to it does not change the corresponding element in the array. This is similar to how assigning to a function parameter has no effect on the argument that was passed to the function.
Your best bet is just to stick to indexing the array like you were before. Use for...of
when you want to iterate over an array and just read it. It doesn't allow for overwriting elements like you're trying to do though.
If you really wanted to use for...of
, you could zip the array to be sorted with another array of indices so you can index when required, but you're losing any readability benefit of for...of
at that point.