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

295
Views
equivalent of python's array.pop() in javascript

I wonder if there's an easy to implement equivalent to python's array.pop() which returns the deleted element while deleting it from the array in parallel in javascript.

let nums = [2, 1, 3, 4, 5, 6];

function sortArray(nums) {
  let arr = new Array();
  let smallest_index;
  for (let j = 0; j < nums.length; j++) {
    smallest_index = find_smallest(nums);
    console.log("smallest", smallest_index);
    arr.push(nums.splice(smallest_index, 1).join(""));
  }

  return arr;
}

function find_smallest(arr) {
  let smallest = arr[0];
  let smallest_index = 0;

  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < smallest) {
      //   console.log("this");
      smallest = arr[i];
      smallest_index = i;
    }
  }
  return smallest_index;
}

it seems that if I replace javascript's (nums.splice(smallest_index, 1).join()) with python's (arr.append(nums.pop(smallest_index)) I would get a perfectly sorted array. is there a similar straightforward solution in javascript as well ?

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

0

OK, you use splice. Here's an example of the implementation below:

Array.prototype.pythonPop = function (index) {
    return this.splice(index, 1)[0];
}

Now, I found the issue, you'll love the answer. So you were using num.length but your methods were augmenting the length of num array. Which is why your answer had only half the needed numbers. See code below. I cached the length prop of nums array

let nums = [2, 1, 3, 4, 5, 6];

function sortArray(nums) {
  let arr = new Array();
  let smallest_index;
  console.log(nums)
  for (let j = 0, length = nums.length; j < length; j++) {
    smallest_index = find_smallest(nums);
    console.log("smallest", smallest_index);
    console.log(nums)
    arr[j] = nums.splice(smallest_index, 1).join("");
  }

  return arr;
}

function find_smallest(arr) {
  let smallest = arr[0];
  let smallest_index = 0;

  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < smallest) {
      //   console.log("this");
      smallest = arr[i];
      smallest_index = i;
    }
  }
  return smallest_index;
}

console.log(sortArray(nums))

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!