Home > Blockchain >  How can I remove an array element at a specific index only using pop?
How can I remove an array element at a specific index only using pop?

Time:10-02

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))

CodePudding user response:

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))

CodePudding user response:

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

  • Related