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

143
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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