0

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 ]

2 Answers2

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)
DecPK
  • 24,537
  • 6
  • 26
  • 42
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.

SSM
  • 2,855
  • 1
  • 3
  • 10