Search code examples
javascriptarrayssplice

How can I remove items from an array having met specific conditions in-place?


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 can loop/map through an array and figure out what numbers are even, so 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 that modifying the original array is not allowed, 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.