Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
Delete even/odd occurance numbers in an array with For Loop

I have an array as shown below, containing 6 numbers. I'm trying to create a function that deletes a value if it's an even/odd occurance. For example, if I type the function deleteData(myArr,"even"), it will remove data number 0th, 2nd, and 4th. And the other way around if it's "odd". But when I tried running my code, it didn't work the way i wanted it to go. Can anybody tell me why?

const myArr=[90,34,28,19,26,22];


function deleteData (array,occuranceType){
    switch (occuranceType){
        case "odd":
            for (let i=0;i<array.length;i++){
                if (i%2!==0){
                    array.splice(i,1);
                };
            };
            break;
        case "even":
            for (let i=0;i<array.length;i++){
                if (i%2==0){
                    array.splice(i,1);
                };
            };
            break;
    };
};

deleteData(arr,"odd")
console.log(arr)

This is the result in the console : [ 90, 28, 19, 22 ]

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use filter for this since it's easier and you don't mutate the original array.

let myArr = [90, 34, 28, 19, 26, 22];

function deleteData(array, removeEven) {
  return array.filter((v, i) => removeEven ? (i % 2 !== 0) : (i % 2 === 0));
};

myArr = deleteData(myArr, true)
console.log(myArr)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can filter the array based on the pos argument passed to the function.

const deleteData = (array, pos) =>
  array.filter((_, i) => i % 2 === Number(pos !== "even"));

console.log(deleteData([90, 34, 28, 19, 26, 22], "odd"));
console.log(deleteData([90, 34, 28, 19, 26, 22], "even"));

Note: Number(false) returns 0 and Number(true) returns 1.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda