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

142
Views
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 answers
Answer question

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 Report

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