Me pregunto si hay un equivalente fácil de implementar a array.pop() de python que devuelve el elemento eliminado mientras lo elimina de la matriz en paralelo en javascript.
let nums = [2, 1, 3, 4, 5, 6]; function sortArray(nums) { let arr = new Array(); let smallest_index; for (let j = 0; j < nums.length; j++) { smallest_index = find_smallest(nums); console.log("smallest", smallest_index); arr.push(nums.splice(smallest_index, 1).join("")); } return arr; } function find_smallest(arr) { let smallest = arr[0]; let smallest_index = 0; for (let i = 1; i < arr.length; i++) { if (arr[i] < smallest) { // console.log("this"); smallest = arr[i]; smallest_index = i; } } return smallest_index; } parece que si reemplazo javascript ( nums.splice(smallest_index, 1).join()) con python (arr.append(nums.pop(smallest_index)) obtendría una matriz perfectamente ordenada. ¿Existe una solución sencilla similar en ¿javascript también?
OK, usa empalme. Aquí hay un ejemplo de la implementación a continuación:
Array.prototype.pythonPop = function (index) { return this.splice(index, 1)[0]; } Ahora, encontré el problema, te encantará la respuesta. Entonces estaba usando num.length pero sus métodos aumentaban la longitud de la matriz num . Es por eso que su respuesta tenía solo la mitad de los números necesarios. Vea el código a continuación. Guardé en caché la propiedad de length de la matriz nums
let nums = [2, 1, 3, 4, 5, 6]; function sortArray(nums) { let arr = new Array(); let smallest_index; console.log(nums) for (let j = 0, length = nums.length; j < length; j++) { smallest_index = find_smallest(nums); console.log("smallest", smallest_index); console.log(nums) arr[j] = nums.splice(smallest_index, 1).join(""); } return arr; } function find_smallest(arr) { let smallest = arr[0]; let smallest_index = 0; for (let i = 1; i < arr.length; i++) { if (arr[i] < smallest) { // console.log("this"); smallest = arr[i]; smallest_index = i; } } return smallest_index; } console.log(sortArray(nums))