I want to create a function in JavaScript that, given an array and an index, the value in that index is removed. For example: removeAt([1,2,3,4],2)
should return [1,2,4]
. The only array method I can use is pop().
I came up with this(wondering if there is a more efficient way to do it):
function removeAt(arr, index) {
var j = 0;
var arr2 = [];
for (var i = 0; i < arr.length - j; i++) {
if (i != index) {
arr2[i] = arr[i + j];
} else {
arr2[i] = arr[i + 1];
j++;
}
}
return arr2
}
console.log(removeAt([1, 2, 3, 4, 5], 3))