Interactive online courses HTML Academy
2026-03-09 14:12 Diff
  • script.js

JavaScript

var usersByDay = [4, 2, 1, 3]; console.log(usersByDay); // Start loop here // Sorting from the first element var currentIndex = 0; var minValue = usersByDay[currentIndex]; for (var j = currentIndex + 1; j <= usersByDay.length - 1; j++) { if (usersByDay[j] < minValue) { minValue = usersByDay[j]; var swap = usersByDay[currentIndex]; usersByDay[currentIndex] = minValue; usersByDay[j] = swap; console.log('Swapping ' + swap + ' and ' + minValue); console.log('Current array: ' + usersByDay); } } console.log('Minimum element ' + minValue + ' is on ' + currentIndex + 'position'); // Complete loop here // Sorting from the second element console.log(usersByDay); currentIndex = 1; minValue = usersByDay[currentIndex]; for (var j = currentIndex + 1; j <= usersByDay.length - 1; j++) { if (usersByDay[j] < minValue) { minValue = usersByDay[j]; var swap = usersByDay[currentIndex]; usersByDay[currentIndex] = minValue; usersByDay[j] = swap; console.log('Swapping ' + swap + ' and ' + minValue); console.log('Current array: ' + usersByDay); } } console.log('Minimum element ' + minValue + ' is on ' + currentIndex + 'position'); // Sorting from the third element console.log(usersByDay); currentIndex = 2; minValue = usersByDay[currentIndex]; for (var j = currentIndex + 1; j <= usersByDay.length - 1; j++) { if (usersByDay[j] < minValue) { minValue = usersByDay[j]; var swap = usersByDay[currentIndex]; usersByDay[currentIndex] = minValue; usersByDay[j] = swap; console.log('Swapping ' + swap + ' and ' + minValue); console.log('Current array: ' + usersByDay); } } console.log('Minimum element ' + minValue + ' is on ' + currentIndex + 'position');

Thanks! We’ll fix everything at once!

Result

  1. Remove the entire code for sorting from the second and third elements.
  2. Then wrap the entire the code after the second line in a loop that increases the variable currentIndex from zero to usersByDay.length - 2 inclusively. Value of currentIndex must increase by one after each iteration.
  3. Inside this loop, remove the duplicate declaration of the variable currentIndex.