This is my code -
function sortArray(arr) {
let newArray = [];
for (let i = 0; i < arr.length; i ) {
let min = Math.min(...arr);
newArray.push(min);
arr.splice(arr.indexOf(min));
}
return newArray;
}
console.log(sortArray([100, 83, 32, 9, 45, 61]));
and it is giving me this output -
[9, 32];
How is this code actually working? it is looping array.length times, so why is it just pushing only two elements inside the newArray?
CodePudding user response:
Two problems there:
When you use splice() with one argument only, it removes not just the given index, but also everything after that. Add the second argument to remove just one item.
arr.length decreases as you remove elements from it, so you need to store the original value to walk through all the values.
function sortArray(arr) { let newArray = []; const length = arr.length; for (let i = 0; i < length; i ) { let min = Math.min(...arr); newArray.push(min); arr.splice(arr.indexOf(min), 1); } return newArray; } console.log(sortArray([100, 83, 32, 9, 45, 61]));
CodePudding user response:
The reason for this is that you put arr.length inside the for loop, and loop you splice 1 array value, so the loop run only 2 times.
try add arr.length to const before the for loop and use it instead of arr.length:
function sortArray(arr) {
let newArray = [];
const arrLength = arr.length;
for (let i = 0; i < arrLength; i ) {
let min = Math.min(...arr);
newArray.push(min);
arr.splice(arr.indexOf(min), 1);
}
return newArray;
}
console.log(sortArray([100, 83, 32, 9, 45, 61]));