You should only add to the result array in the if condition, not else. Use j as the index in the result, don't add or subtract it.

function removeAt(arr, index) {
  var j = 0;
  var arr2 = [];
  for (var i = 0; i < arr.length; i++) {
    if (i != index) {
      arr2[j] = arr[i];
      j++;
    }
  }
  return arr2
}

console.log(removeAt([1, 2, 3, 4, 5], 3))

Answer from Barmar on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › pop
Array.prototype.pop() - JavaScript | MDN
The pop() method of Array instances removes the last element from an array and returns that element. This method changes the length of the array.
🌐
W3Schools
w3schools.com › jsref › jsref_pop.asp
JavaScript Array pop() Method
Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean ·
🌐
PHP
php.net › manual › en › function.array-pop.php
PHP: array_pop - Manual
Strict Standards will be thrown out if you put exploded array in array_pop: <?php $a = array_pop(explode(",", "a,b,c")); echo $a; ?> You will see: PHP Strict Standards: Only variables should be passed by reference in - on line 2 Strict Standards: Only variables should be passed by reference in - on line 2 c Notice that, you should assign a variable for function explode, then pass the variable reference into array_pop to avoid the Strict Standard warning. ... In a previous example ... <?php function array_trim ( $array, $index ) { if ( is_array ( $array ) ) { unset ( $array[$index] ); array_unshift ( $array, array_shift ( $array ) ); return $array; } else { return false; } } ?> This have a problem.
🌐
Educative
educative.io › answers › what-is-the-array-pop-method-in-python
What is the array pop() method in Python?
The pop() method takes the item’s index position to be removed from the given array.
🌐
freeCodeCamp
freecodecamp.org › news › python-pop-how-to-pop-from-a-list-or-an-array-in-python
Python .pop() – How to Pop from a List or an Array in Python
March 1, 2022 - By default, if there is no index specified, the pop() method will remove the last item that is contained in the list.
Top answer
1 of 16
17014

Find the index of the array element you want to remove using indexOf, and then remove that index with splice.

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
  array.splice(index, 1); // 2nd parameter means remove one item only
}

// array = [2, 9]
console.log(array);

The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.


For completeness, here are functions. The first function removes only a single occurrence (e.g., removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:

function removeItemOnce(arr, value) {
  var index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}

function removeItemAll(arr, value) {
  var i = 0;
  while (i < arr.length) {
    if (arr[i] === value) {
      arr.splice(i, 1);
    } else {
      ++i;
    }
  }
  return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))

In TypeScript, these functions can stay type-safe with a type parameter:

function removeItem<T>(arr: Array<T>, value: T): Array<T> {
  const index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}
2 of 16
2616
  • Do it simple, intuitive and explicit (Occam's razor)
  • Do it immutable (original array stays unchanged)
  • Do it with standard JavaScript functions, if your browser doesn't support them - use polyfill

In this code example I use array.filter(...) function to remove unwanted items from an array. This function doesn't change the original array and creates a new one. If your browser doesn't support this function (e.g. Internet Explorer before version 9, or Firefox before version 1.5), consider polyfilling with core-js.

Be mindful though, creating a new array every time takes a big performance hit. If the list is very large (think 10k+ items) then consider using other methods.

Removing item (ECMA-262 Edition 5 code AKA old style JavaScript)

var value = 3

var arr = [1, 2, 3, 4, 5, 3]

arr = arr.filter(function(item) {
    return item !== value
})

console.log(arr)
// [ 1, 2, 4, 5 ]

Removing item (ECMAScript 6 code)

let value = 3

let arr = [1, 2, 3, 4, 5, 3]

arr = arr.filter(item => item !== value)

console.log(arr)
// [ 1, 2, 4, 5 ]

IMPORTANT ECMAScript 6 () => {} arrow function syntax is not supported in Internet Explorer at all, Chrome before version 45, Firefox before version 22, and Safari before version 10. To use ECMAScript 6 syntax in old browsers you can use BabelJS.


Removing multiple items (ECMAScript 7 code)

An additional advantage of this method is that you can remove multiple items

let forDeletion = [2, 3, 5]

let arr = [1, 2, 3, 4, 5, 3]

arr = arr.filter(item => !forDeletion.includes(item))
// !!! Read below about array.includes(...) support !!!

console.log(arr)
// [ 1, 4 ]

IMPORTANT array.includes(...) function is not supported in Internet Explorer at all, Chrome before version 47, Firefox before version 43, Safari before version 9, and Edge before version 14 but you can polyfill with core-js.

Removing multiple items (in the future, maybe)

If the "This-Binding Syntax" proposal is ever accepted, you'll be able to do this:

// array-lib.js

export function remove(...forDeletion) {
    return this.filter(item => !forDeletion.includes(item))
}

// main.js

import { remove } from './array-lib.js'

let arr = [1, 2, 3, 4, 5, 3]

// :: This-Binding Syntax Proposal
// using "remove" function as "virtual method"
// without extending Array.prototype
arr = arr::remove(2, 3, 5)

console.log(arr)
// [ 1, 4 ]

Try it yourself in BabelJS :)

Reference

  • Array.prototype.includes
  • Functional composition
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-list-pop-method
Python List pop() Method - GeeksforGeeks
September 11, 2025 - Explanation: a.pop() removes the last element, which is 40. The list a is now [10, 20, 30]. ... index (optional): index of an item to remove.
Find elsewhere
🌐
W3Schools
w3schools.com › js › js_array_methods.asp
JavaScript Array Methods
Shifting is equivalent to popping, but working on the first element instead of the last. The shift() method removes the first array element and "shifts" all other elements to a lower index.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › splice
Array.prototype.splice() - JavaScript | MDN
Indexed collections guide · Array · Array.prototype.concat() Array.prototype.push() Array.prototype.pop() Array.prototype.shift() Array.prototype.slice() Array.prototype.toSpliced() Array.prototype.unshift() Was this page helpful to you? Yes · No Learn how to contribute ·
🌐
DEV Community
dev.to › tochi_ › javascript-array-methods-under-the-hood-push-and-pop-explained-1e59
JavaScript Array Methods Under the Hood: Push and Pop Explained - DEV Community
July 31, 2025 - If you have an array of length n, the last item is at index n - 1. To remove it, you just ignore that index and reduce the array's length by 1. const numArray = [1, 2, 5, 4]; const jsPop = (arr) => { arr.length = arr.length - 1; return arr; ...
🌐
Love2Dev
love2dev.com › blog › javascript-remove-from-array
9 Ways To Remove 🗑️ Elements From A JavaScript Array 📇[Examples]
pop - Removes from the End of an Array · shift - Removes from the beginning of an Array · splice - removes from a specific Array index · filter - allows you to programatically remove elements from an Array · You will also learn some other ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array
Array - JavaScript | MDN
JavaScript arrays are not associative arrays and so, array elements cannot be accessed using arbitrary strings as indexes, but must be accessed using nonnegative integers (or their respective string form) as indexes.
Top answer
1 of 2
2

When you delete an element, all the elements after it renumber: the n+1th element becomes nth element, etc. But you progress to the next n anyway. This is why you are skipping some elements.

In the first snippet, you pre-construct the list of indices to iterate over; but as the list shortens, some of the later indices will not exist any more.

In the second snippet, you compare with the actual length of the list on each iteration, so you never get an invalid index.

Also note that bool is not needed whenever you are evaluating a condition, as it is implicitly applied in such a context.

In order to do this correctly, you have two choices:

  • iterate from end of the list backwards. If you delete an element, the elements in front of it do not get renumbered.

    for n in range(len(lst) - 1, -1, -1):
        if not lst[n]:
            lst.pop(n)
    
  • using the while method, make sure to either increment n (moving n closer to the end of the list), or delete an element (moving the end of the list closer to n); never both at the same time. This will ensure no skipping.

    n = 0
    while n < len(lst):
        if not lst[n]:
            lst.pop(n)
        else:
            n += 1
    

The third option is to avoid the index loop altogether, and do it more pythonically, generating a new list using a comprehension with a filtering condition, or filter.

new_lst = list(filter(bool, lst))

or

new_lst = [e for e in lst if e]

or, if you really want to change the original list, replace its content like this:

lst[:] = filter(bool, lst)
2 of 2
0

Index out of range error: lst.pop(n) This will pop element from the list but for n in range(len(lst)-1) will still loop through the lst assuming same length as original.

To avoid this start loop from last index in reverse order so that even after pop values will still be present for indexes yet to be read.

   def compact(lst):
    for n in range(len(lst)-1,-1,-1):                  
        if not bool(lst[n]):
            lst.pop(n)
    return lst

    ls = [0, 1, 2, '', '',[], False, (), None, 'All done','']
    print(compact(ls))

    # Output:
    # [1, 2, 'All done']
🌐
Mimo
mimo.org › glossary › javascript › array-pop
JavaScript Array pop() method: Syntax, Usage, and Examples
The pop() method in JavaScript removes the last element from an array and returns that element. It changes the original array by reducing its length by one. The JavaScript array pop method is often used when working with stacks, where the last item added is the first one removed (LIFO – Last ...
🌐
freeCodeCamp
freecodecamp.org › news › python-list-pop-how-to-pop-an-element-from-a-array
Python list.pop() – How to Pop an Element from a Array
February 9, 2023 - You can use the pop() method to either remove a specific element in a list or to remove the last element. When a parameter is used, you can specify the particular element (using the element's index number) to be removed.
🌐
Sentry
sentry.io › sentry answers › javascript › how can i remove a specific item from an array?
How Can I Remove a Specific Item from an Array? | Sentry
If you want to remove an item from an array, you can use the `pop()` method to remove the last element or the `shift()` method to remove the first element. However, if the item you want to remove is not the first or last element, these methods ...