Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
Eliminar elemento de una matriz usando una función

Estoy tratando de construir una función que elimine un elemento de una matriz. Tanto la matriz como el elemento se configuran usando parámetros que se presionan cuando llamo a la función.

Sin embargo, no devuelve el [1,2,4] esperado, sino que devuelve "todavía no", una cadena que incorporé en una declaración if para devolver si falla.

Puedo ver en un registro de consola la variable emergente = 3 y el bucle for actual está recorriendo correctamente todas las opciones. Entonces, ¿por qué no funciona?

 const removeFromArray = function() { let args = Array.from(arguments); let popped = args.pop(); for (i = 0; i < args.length; i++) { let current = args[i]; if (current === popped) { console.log(args); return args; } else { console.log("not yet"); } } }; removeFromArray([1, 2, 3, 4], 3);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Ok, comenté su código, los problemas que contiene y realicé los cambios correspondientes para que funcione como usted quería:

 const removeFromArray = function() { // arguments is not [1, 2, 3, 4, 3], but instead it's [[1, 2, 3, 4], 3] (length is 2, remember this later) let args = Array.from(arguments); // pop works correctly and returns 3 let popped = args.pop(); // here we cannot loop with args.length, as it is 2 // if we change args.length to args[0].length, this will work for (i = 0; i < args[0].length; i++) { // args[i] won't work here for the same reason args.length didn't work, // because we're targeting a wrong thing // if we change this to args[0][i], it will work let current = args[0][i]; // After the changes, this if will work correctly if (current === popped) { // We can't just return args // A) we're once again targeting and wrong thing // B) we haven't removed anything yet // so lets change this to first splice the array (remove the wanted value) args[0].splice(i, 1); // and then return the array where the wanted value is removed return args[0]; } } }; const newArray = removeFromArray([1, 2, 3, 4], 3); // output the returned new array where 3 is removed console.log(newArray)

El principal problema es que args no contiene lo que pensabas que contiene (la matriz de números), en realidad es args[0] el que lo contiene.

La otra cosa fue que cuando encontró el valor que quería eliminar de la matriz, en realidad nunca lo eliminó. Así que aquí usamos el empalme para eliminar el valor antes de regresar.

about 4 years ago · Juan Pablo Isaza Relatório

0

 const removeFromArray = function (array, itemToRemove) { return array.filter(item => item !== itemToRemove); };
about 4 years ago · Juan Pablo Isaza Relatório

0

No sé por qué no usas ninguna función integrada de JS como

 let removeFromArray = (arr, remove) => arr.filter(x => x != remove) let filteredArray = removeFromArray([1, 2, 3, 4], 3)

Pero hagámoslo a tu manera

 const removeFromArray(arr, remove) { const items = []; for (const item of arr) { if (item != remove) items.push(item) } return items; }; removeFromArray([1, 2, 3, 4], 3);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda