Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I remove items from an array having met specific conditions using splice?

I am working on what i thought is a simple algorithm:

Task: Look at the given array, take only the even numbers and multiply them by 2. The catch is to modify the array in its place and NOT create a new array.

I need to loop/map through an array, figure out what numbers are even:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I got this far:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

arr.forEach((x, y) => {
        if (x % 2 !== 0) {
           // I would like to splice those numbers, 
           // but can't figure out how to do it?
        } 
    })

Again, the catch is modifying the original array, returning 4, 8, 12, 16, and 20.

>Solution :

This is not a good approach in my opinion, but if you insist on modifying the existing array without creating a new one, this should do the job:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let i = 0;
while (i < arr.length) {
    if (arr[i] % 2 === 0) {
        arr[i] *= 2;
    } else {
        arr.splice(i, 1);
        i--;
    }
    i++;
}

console.log(arr.join(", "));

The i– comes into play, because when you splice the current index (where the next element will be after the splice) and you execute i++, it’s going to skip the current index. The same effect can possibly be achieved by adding i++ in the if block and remove the i– in the else block.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading