Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
Elimine elementos de matriz particulares y empújelos hacia la parte posterior de la matriz

Intentando eliminar todos los 0 de una matriz y devolverlos en la misma matriz

Entonces, por ejemplo, si tengo esto como una matriz

 let arrThree = [9,0,9,1,2,1,1,3,1,9,0,0,9,0,0,0,0,0,0,0]

obtendría esto:

 let arrThree = [9,9,9,1,2,1,1,3,1,9,9,0,0,0,0,0,0,0,0,0,0,0]

Esto es lo que escribí:

 var remove = function (arr) { let test = []; for(let i = 0; i < arr.length; i++){ arr[i] === 0 ? test.push(arr.splice(i,1)) : false //if i is 0 then we want to push that into another array } arr.push(...test) return [].concat(...arr) }

Cuando ejecuto esta función me sale esto

 [ 9, 9, 1, 2, 1, 1, 3, 1, 9, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

¿No estoy seguro de dónde me estoy equivocando?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

El problema con su código es que cambia la longitud de arr con arr.splice(i,1) . Esto estropea la condición del ciclo i < arr.length .

Para corregir su código, puede recorrer hacia atrás la matriz. Entonces, a medida que la longitud de la matriz se acorta, i sigue siendo válida.

 let arrThree = [9,0,9,1,2,1,1,3,1,9,0,0,9,0,0,0,0,0,0,0]; var remove = function(arr) { let test = []; for(let i = arr.length - 1; i >= 0; --i) { if (arr[i] === 0) test.push(arr.splice(i, 1)[0]); } return arr.concat(test); } console.log(remove(arrThree));

Hay algunas otras maneras de hacer esto. Una es usar el filter para crear 2 matrices, una sin 0 y otra con 0 y unirlas:

 let arrThree = [9,0,9,1,2,1,1,3,1,9,0,0,9,0,0,0,0,0,0,0]; let remove = (arr) => arr.filter(i => i != 0).concat(arr.filter(i => i == 0)); console.log(remove(arrThree));

about 4 years ago · Juan Pablo Isaza Report

0

Solo necesita dos iteraciones, una para encontrar valores distintos de cero y otra para poner ceros en el lado derecho hasta el final de la matriz. No necesita empujar o empalmar matrices.

 const move0 = array => { let i = 0, j = 0; while (i < array.length) { if (array[i]) array[j++] = array[i]; i++; } while (j < array.length) { array[j] = '#'; // in reality it is zero j++; } }, array = [9, 0, 9, 1, 2, 1, 1, 3, 1, 9, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0]; move0(array) console.log(...array);

about 4 years ago · Juan Pablo Isaza Report

0

Si no necesita ordenar los elementos distintos de cero, una solución bastante eficiente sería intercambiar el 0 más a la izquierda con el elemento distinto de cero más a la derecha. Una vez que sus índices para rastrear dónde se encuentra a la izquierda y a la derecha se crucen, sabrá que ha terminado.

 function moveZeros(arr) { let i = 0; let j = arr.length - 1; while(i < j) { // Found a 0 to the left of a non-zero, swap. if(arr[i] == 0 && arr[j] != 0) { let tmp = arr[j]; arr[j] = arr[i]; arr[i] = tmp; } // Find a zero if(arr[i] != 0) { i++; } // Find a non-zero if(arr[j] == 0) { j--; } } return arr; } console.log(moveZeros([1,2,0,3,0,0,0])); console.log(moveZeros([9,0,9,1,2,1,1,3,1,9,0,0,9,0,0,0,0,0,0,0]));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!