Quiero ordenar una matriz del número más bajo al más alto. Pero cuando ejecuto el siguiente código, ¡se pierden algunos de los elementos de mi matriz! no sé por qué Necesito ayuda.`// Ordenar una matriz de menor a mayor
function findSmallest(numArr) { let smallestNumber = numArr[0] for (let i = 0; i < numArr.length; i++) { if (numArr[i + 1] < smallestNumber) { smallestNumber = numArr[i + 1] } } return smallestNumber; } function getSortedArray(arr) { let sortedArray = [] for (j = 0; j < arr.length; j++) { let smallest = findSmallest(arr) let smallestNumbmerIndex; for (let i = 0; i < arr.length; i++) { if (arr[i] === smallest) { smallestNumbmerIndex = i } } arr.splice(smallestNumbmerIndex, 1) sortedArray.push(smallest) } return sortedArray } let myArr = [23, 2, 12, 4] console.log(getSortedArray(myArr)) // console output => [2, 4] , the rest elements get omitteddado que arr se reduce en cada iteración, su ciclo for no ejecutará 4 iteraciones, solo 2 -
usa while(arr.length){ en lugar del bucle for j
function findSmallest(numArr) { let smallestNumber = numArr[0] for (let i = 0; i < numArr.length; i++) { if (numArr[i + 1] < smallestNumber) { smallestNumber = numArr[i + 1] } } return smallestNumber; } function getSortedArray(arr) { let sortedArray = [] while(arr.length) { let smallest = findSmallest(arr) let smallestNumbmerIndex; for (let i = 0; i < arr.length; i++) { if (arr[i] === smallest) { smallestNumbmerIndex = i } } arr.splice(smallestNumbmerIndex, 1) sortedArray.push(smallest) } return sortedArray } let myArr = [23, 2, 12, 4] console.log(getSortedArray(myArr)) // console output => [2, 4] , the rest elements get omittedPodemos usar un ciclo while, o podemos almacenar la longitud de la matriz en una variable antes del ciclo for, para que no cambie:
function findSmallest(numArr) { let smallestNumber = numArr[0] for (let i = 0; i < numArr.length; i++) { if (numArr[i + 1] < smallestNumber) { smallestNumber = numArr[i + 1] } } return smallestNumber; } function getSortedArray(arr) { let sortedArray = [] // we can store the array length into a variable let length = arr.length for (j = 0; j < length; j++) { let smallest = findSmallest(arr) let smallestNumbmerIndex; for (let i = 0; i < arr.length; i++) { if (arr[i] === smallest) { smallestNumbmerIndex = i } } arr.splice(smallestNumbmerIndex, 1) sortedArray.push(smallest) } return sortedArray } let myArr = [23, 2, 12, 4] console.log(getSortedArray(myArr))