JavaScript Array Tips: How to Remove Elements at a Specific Index

Estimated read time 1 min read

In many interviews, it’s a common question for the applicants that you’re asked to remove any element from an array without using the array methods.

I have written the following JavaScript function that takes an array and removes an element from the list.

const num = [12, 23, 34, 23, 54, 34, 23, 45];
let position = 5;

function deleteElement(arr, element) {
    // Check if the element position is within array bounds
    if (element >= arr.length || element < 0) {
        console.error("Invalid position");
        return;
    }

    for (let i = element; i < arr.length - 1; i++) {
        arr[i] = arr[i + 1];
    }
    
    // Reduce the length of the array by 1
    arr.length = arr.length - 1;
    
    console.log(arr);
}

deleteElement(num, position);

You May Also Like

More From Author