Home > Software design >  Javascript version of list.pop
Javascript version of list.pop

Time:01-12

I am trying to create a javascript version of python's pop function.

Here is what I have so far:

function pop(arr, idx) {
  arr = arr.splice(0, idx).concat(arr.splice(idx   1));
  console.log(arr);
}

I am not sure of why it is only returning the first part and not combining with the second.

CodePudding user response:

are you looking for something like this? maybe you can modify it so that the pop function returns the removed element.

const arr1 =  [10,20,30,40,50,60];
const arr2 =  [10,20,30,40,50,60];
const arr3 =  [10,20,30,40,50,60];

function pop(arr, idx) {
    removedEl = arr.splice(idx,1)[0];
  console.log('removed element: ',removedEl)
  console.log('final array: ',arr);
}

pop(arr1,0);
pop(arr2,2);
pop(arr3,5)

CodePudding user response:

Array.splice() modifies the array. It doesn't create a new array. All you need is this:

const pythonPop = ( arr , i = -1 ) => arr.splice(i,1)[0];
  •  Tags:  
  • Related