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))
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;
}
You can simply use Array.prototype.splice.
function removeAt(arr, idx){
return arr.splice(idx, 1);
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
Array.prototype.pop will only remove the last element and you'd have to do unnecessary operations with the array to achieve it.