Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
How can I remove an array element at a specific index only using pop?

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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;  
}
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!