Home > Net >  equivalent of python's array.pop() in javascript
equivalent of python's array.pop() in javascript

Time:07-02

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 ?

CodePudding user response:

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

  • Related