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 OverflowVideos
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))
If you are not allowed to use any Array function except pop(), you may save memory space by not creating an extra variable using it.
function removeAt(arr, index){
if(index>arr.length-1 || index<0) return arr;
for(let i=0; i<arr.length; i++) {
if(i>=index) {
arr[i] = arr[i+1];
}
}
arr.pop();
return arr;
}
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;
}
- 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
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
whilemethod, make sure to either incrementn(movingncloser to the end of the list), or delete an element (moving the end of the list closer ton); 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)
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']
You can use array_values for that like as
$array = [
0 => 'apple',
1 => 'banana',
2 => 'orange',
3 => 'grapes'
];
unset($array[1]);
print_r(array_values($array));
you will have to create a custom function
function removeAndreindex($array,$index)
{
unset($array[$index]);
return array_values($array)
}
Thanks
There is no pop method for NumPy arrays, but you could just use basic slicing (which would be efficient since it returns a view, not a copy):
In [104]: y = np.arange(5); y
Out[105]: array([0, 1, 2, 3, 4])
In [106]: last, y = y[-1], y[:-1]
In [107]: last, y
Out[107]: (4, array([0, 1, 2, 3]))
If there were a pop method it would return the last value in y and modify y.
Above,
last, y = y[-1], y[:-1]
assigns the last value to the variable last and modifies y.
Here is one example using numpy.delete():
import numpy as np
arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(arr)
# array([[ 1, 2, 3, 4],
# [ 5, 6, 7, 8],
# [ 9, 10, 11, 12]])
arr = np.delete(arr, 1, 0)
print(arr)
# array([[ 1, 2, 3, 4],
# [ 9, 10, 11, 12]])