Pop the last item off of an array without using built in the array.pop() function












1















I'm trying to complete a problem that involves removing the last item of an array without using the built-in .pop function. Here is the full problem...



Write a function which accepts an array.



The function should remove the last value in the array and return the value removed or undefined if the array is empty.



Do not use the built in Array.pop() function!



Example:



var arr = [1, 2, 3, 4];
pop(arr); // 4


I figured out how to grab the last number with the following code but this obviously doesn't solve the problem.






function pop (array){
for (i=array.length-1; i>array.length-2; i--){
array = array[i]
} return array
}
pop ([1,2,3,4])





Thanks in advance!










share|improve this question




















  • 1





    Try with slice() ... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – LGSon
    Nov 23 '18 at 20:12













  • simple, array.reverse().shift() then reverse it again..

    – rlemon
    Nov 23 '18 at 20:15













  • First check the array length. If it is zero, return undefined. Otherwise, save the last array element in a local variable (using length-1 to access it). Then decrement the length, and return that local variable.

    – Michael Geary
    Nov 23 '18 at 20:21


















1















I'm trying to complete a problem that involves removing the last item of an array without using the built-in .pop function. Here is the full problem...



Write a function which accepts an array.



The function should remove the last value in the array and return the value removed or undefined if the array is empty.



Do not use the built in Array.pop() function!



Example:



var arr = [1, 2, 3, 4];
pop(arr); // 4


I figured out how to grab the last number with the following code but this obviously doesn't solve the problem.






function pop (array){
for (i=array.length-1; i>array.length-2; i--){
array = array[i]
} return array
}
pop ([1,2,3,4])





Thanks in advance!










share|improve this question




















  • 1





    Try with slice() ... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – LGSon
    Nov 23 '18 at 20:12













  • simple, array.reverse().shift() then reverse it again..

    – rlemon
    Nov 23 '18 at 20:15













  • First check the array length. If it is zero, return undefined. Otherwise, save the last array element in a local variable (using length-1 to access it). Then decrement the length, and return that local variable.

    – Michael Geary
    Nov 23 '18 at 20:21
















1












1








1








I'm trying to complete a problem that involves removing the last item of an array without using the built-in .pop function. Here is the full problem...



Write a function which accepts an array.



The function should remove the last value in the array and return the value removed or undefined if the array is empty.



Do not use the built in Array.pop() function!



Example:



var arr = [1, 2, 3, 4];
pop(arr); // 4


I figured out how to grab the last number with the following code but this obviously doesn't solve the problem.






function pop (array){
for (i=array.length-1; i>array.length-2; i--){
array = array[i]
} return array
}
pop ([1,2,3,4])





Thanks in advance!










share|improve this question
















I'm trying to complete a problem that involves removing the last item of an array without using the built-in .pop function. Here is the full problem...



Write a function which accepts an array.



The function should remove the last value in the array and return the value removed or undefined if the array is empty.



Do not use the built in Array.pop() function!



Example:



var arr = [1, 2, 3, 4];
pop(arr); // 4


I figured out how to grab the last number with the following code but this obviously doesn't solve the problem.






function pop (array){
for (i=array.length-1; i>array.length-2; i--){
array = array[i]
} return array
}
pop ([1,2,3,4])





Thanks in advance!






function pop (array){
for (i=array.length-1; i>array.length-2; i--){
array = array[i]
} return array
}
pop ([1,2,3,4])





function pop (array){
for (i=array.length-1; i>array.length-2; i--){
array = array[i]
} return array
}
pop ([1,2,3,4])






javascript arrays






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 20:17









Scott Marcus

38.8k52036




38.8k52036










asked Nov 23 '18 at 20:11









Marsden MarsMarsden Mars

254




254








  • 1





    Try with slice() ... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – LGSon
    Nov 23 '18 at 20:12













  • simple, array.reverse().shift() then reverse it again..

    – rlemon
    Nov 23 '18 at 20:15













  • First check the array length. If it is zero, return undefined. Otherwise, save the last array element in a local variable (using length-1 to access it). Then decrement the length, and return that local variable.

    – Michael Geary
    Nov 23 '18 at 20:21
















  • 1





    Try with slice() ... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – LGSon
    Nov 23 '18 at 20:12













  • simple, array.reverse().shift() then reverse it again..

    – rlemon
    Nov 23 '18 at 20:15













  • First check the array length. If it is zero, return undefined. Otherwise, save the last array element in a local variable (using length-1 to access it). Then decrement the length, and return that local variable.

    – Michael Geary
    Nov 23 '18 at 20:21










1




1





Try with slice() ... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

– LGSon
Nov 23 '18 at 20:12







Try with slice() ... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

– LGSon
Nov 23 '18 at 20:12















simple, array.reverse().shift() then reverse it again..

– rlemon
Nov 23 '18 at 20:15







simple, array.reverse().shift() then reverse it again..

– rlemon
Nov 23 '18 at 20:15















First check the array length. If it is zero, return undefined. Otherwise, save the last array element in a local variable (using length-1 to access it). Then decrement the length, and return that local variable.

– Michael Geary
Nov 23 '18 at 20:21







First check the array length. If it is zero, return undefined. Otherwise, save the last array element in a local variable (using length-1 to access it). Then decrement the length, and return that local variable.

– Michael Geary
Nov 23 '18 at 20:21














6 Answers
6






active

oldest

votes


















0














EDIT: This includes a null and empty check.






var array = [1, 2, 3, 4, 5];

function pop(array) {
return array && array.splice(-1)[0]
}

console.log(pop(array));
console.log(pop(array));
console.log(pop(array));
console.log(pop(array));
console.log(pop(array));
console.log(pop(array));
console.log(array);








share|improve this answer


























  • This doesn't meet the requirements

    – Wayne Phipps
    Nov 23 '18 at 20:23






  • 2





    Yep, now you're returning an array. :)

    – Mark Meyer
    Nov 23 '18 at 20:27








  • 1





    Haha @MarkMeyer , none of us are reading. Updated.

    – Marius
    Nov 23 '18 at 20:30






  • 1





    This worked, thanks so much!

    – Marsden Mars
    Nov 23 '18 at 20:32






  • 1





    @Marius Try repeating the console.log(pop(array)) at the end of your snippet a few times, and then add a console.log(array) at the end, and see what it logs. Does the code do what the problem specification requires?

    – Michael Geary
    Nov 23 '18 at 23:39



















4














A much simpler solution is to just decrease the length of the array by one. No need to create a second array.






function pop (array){
let last = array[array.length-1]; // Store last item in array
array.length = array.length > 0 ? array.length - 1 : 0; // Decrease length
return last; // Return last item
}

// Test function
function logger(ary){
console.log("Original array: " + ary.join(", "), "ntItem popped off: " + pop(ary), "ntArray contents now: " + ary.join(", "));
}

// Tests
var ary = [1,2,3,4]; logger(ary);
var ary = ["red", "white", "blue", "green"]; logger(ary);
var ary = ["onlyItem"]; logger(ary);
var ary = ; logger(ary);
var ary = [false]; logger(ary);








share|improve this answer





















  • 1





    @ScottMarcus just return last;

    – Thomas
    Nov 23 '18 at 20:34











  • @Thomas LOL, yeah. That works too!

    – Scott Marcus
    Nov 23 '18 at 20:35



















2














It seems like simple is better in this case:






const example = [1,2,3,4];

function pop(arr) {
return arr && arr.splice(-1)[0]
}
console.log(pop(example))
console.log(pop(example))
console.log(pop(example))
console.log(pop(example))
console.log(pop(example))

// edge case: should it return undefined or should it throw?
console.log(pop())








share|improve this answer


























  • This is a really good take on the problem. Simple solution.

    – Marius
    Nov 24 '18 at 19:21











  • Thanks, i learnt something.

    – Marius
    Nov 24 '18 at 19:22



















0














I think what you are looking for is Array.prototype.slice(). You can use the length property of the array to determine whether it is empty and then return the last entry using slice.






const example = [1,2,3,4];
const emptyExample = ;

const pop = group => group.length > 0
? group.slice(group.length - 1)[0]
: undefined;

const answers = [ pop(example), pop(emptyExample) ];
console.log(answers);





Edit from comment



Example should remove from the array while returning last entry so Array.prototype.splice is probably the better function here.






const example = [1,2,3,4];
const emptyExample = ;

const pop = group => (Array.isArray(group) && group.length > 0)
? group.splice(group.length - 1, 1)[0]
: undefined;

const initialExample = [ ...example ];
const answers = [
pop(example),
pop(emptyExample),
{ initialExample, updatedExample: example, emptyExample }
];
console.log(answers);








share|improve this answer

































    0















    Array.prototype.splice(start[, deleteCount[, item1[, item2[, ...]]]])



    The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

    ...

    Return value: An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.



    - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice




    What this means is that so long as the input to the function is an instance of Array, we can call Array#splice(-1) to remove the last element. If there are no elements, this will return an empty array. Because we will always be getting either an array with one element or an empty array, we can access the first element using [0]. If the array is empty, this will be undefined.



    So, check that that input is an array, then return Array#splice(-1)[0] if it is or undefined if it is not.






    function pop(input) {
    let output;
    if(input instanceof Array) {
    output = input.splice(-1)[0]
    }
    return output
    }

    function test(input) {
    console.log({
    before: input && Array.from(input),
    popped: pop(input),
    after: input
    })
    return test
    }

    test( [ 1, 2, 3, 4 ] )( [ 1 ] )( [ ] )( )( [ , , , ] )








    share|improve this answer































      -1














      You could use Array.splice()



      function pop(arr) {
      return arr.splice(-1)[0];
      }


      This will delete the last item in the array and return it.






      share|improve this answer


























      • This is pretty close, but has a couple of problems. The parameter name is not spelled consistently in the code, and if that is fixed, the return value is not correct. (It's almost correct, but read the problem description again.)

        – Michael Geary
        Nov 24 '18 at 4:24











      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53452458%2fpop-the-last-item-off-of-an-array-without-using-built-in-the-array-pop-functio%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      6 Answers
      6






      active

      oldest

      votes








      6 Answers
      6






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      EDIT: This includes a null and empty check.






      var array = [1, 2, 3, 4, 5];

      function pop(array) {
      return array && array.splice(-1)[0]
      }

      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(array);








      share|improve this answer


























      • This doesn't meet the requirements

        – Wayne Phipps
        Nov 23 '18 at 20:23






      • 2





        Yep, now you're returning an array. :)

        – Mark Meyer
        Nov 23 '18 at 20:27








      • 1





        Haha @MarkMeyer , none of us are reading. Updated.

        – Marius
        Nov 23 '18 at 20:30






      • 1





        This worked, thanks so much!

        – Marsden Mars
        Nov 23 '18 at 20:32






      • 1





        @Marius Try repeating the console.log(pop(array)) at the end of your snippet a few times, and then add a console.log(array) at the end, and see what it logs. Does the code do what the problem specification requires?

        – Michael Geary
        Nov 23 '18 at 23:39
















      0














      EDIT: This includes a null and empty check.






      var array = [1, 2, 3, 4, 5];

      function pop(array) {
      return array && array.splice(-1)[0]
      }

      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(array);








      share|improve this answer


























      • This doesn't meet the requirements

        – Wayne Phipps
        Nov 23 '18 at 20:23






      • 2





        Yep, now you're returning an array. :)

        – Mark Meyer
        Nov 23 '18 at 20:27








      • 1





        Haha @MarkMeyer , none of us are reading. Updated.

        – Marius
        Nov 23 '18 at 20:30






      • 1





        This worked, thanks so much!

        – Marsden Mars
        Nov 23 '18 at 20:32






      • 1





        @Marius Try repeating the console.log(pop(array)) at the end of your snippet a few times, and then add a console.log(array) at the end, and see what it logs. Does the code do what the problem specification requires?

        – Michael Geary
        Nov 23 '18 at 23:39














      0












      0








      0







      EDIT: This includes a null and empty check.






      var array = [1, 2, 3, 4, 5];

      function pop(array) {
      return array && array.splice(-1)[0]
      }

      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(array);








      share|improve this answer















      EDIT: This includes a null and empty check.






      var array = [1, 2, 3, 4, 5];

      function pop(array) {
      return array && array.splice(-1)[0]
      }

      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(array);








      var array = [1, 2, 3, 4, 5];

      function pop(array) {
      return array && array.splice(-1)[0]
      }

      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(array);





      var array = [1, 2, 3, 4, 5];

      function pop(array) {
      return array && array.splice(-1)[0]
      }

      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(pop(array));
      console.log(array);






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 24 '18 at 19:33

























      answered Nov 23 '18 at 20:15









      MariusMarius

      867




      867













      • This doesn't meet the requirements

        – Wayne Phipps
        Nov 23 '18 at 20:23






      • 2





        Yep, now you're returning an array. :)

        – Mark Meyer
        Nov 23 '18 at 20:27








      • 1





        Haha @MarkMeyer , none of us are reading. Updated.

        – Marius
        Nov 23 '18 at 20:30






      • 1





        This worked, thanks so much!

        – Marsden Mars
        Nov 23 '18 at 20:32






      • 1





        @Marius Try repeating the console.log(pop(array)) at the end of your snippet a few times, and then add a console.log(array) at the end, and see what it logs. Does the code do what the problem specification requires?

        – Michael Geary
        Nov 23 '18 at 23:39



















      • This doesn't meet the requirements

        – Wayne Phipps
        Nov 23 '18 at 20:23






      • 2





        Yep, now you're returning an array. :)

        – Mark Meyer
        Nov 23 '18 at 20:27








      • 1





        Haha @MarkMeyer , none of us are reading. Updated.

        – Marius
        Nov 23 '18 at 20:30






      • 1





        This worked, thanks so much!

        – Marsden Mars
        Nov 23 '18 at 20:32






      • 1





        @Marius Try repeating the console.log(pop(array)) at the end of your snippet a few times, and then add a console.log(array) at the end, and see what it logs. Does the code do what the problem specification requires?

        – Michael Geary
        Nov 23 '18 at 23:39

















      This doesn't meet the requirements

      – Wayne Phipps
      Nov 23 '18 at 20:23





      This doesn't meet the requirements

      – Wayne Phipps
      Nov 23 '18 at 20:23




      2




      2





      Yep, now you're returning an array. :)

      – Mark Meyer
      Nov 23 '18 at 20:27







      Yep, now you're returning an array. :)

      – Mark Meyer
      Nov 23 '18 at 20:27






      1




      1





      Haha @MarkMeyer , none of us are reading. Updated.

      – Marius
      Nov 23 '18 at 20:30





      Haha @MarkMeyer , none of us are reading. Updated.

      – Marius
      Nov 23 '18 at 20:30




      1




      1





      This worked, thanks so much!

      – Marsden Mars
      Nov 23 '18 at 20:32





      This worked, thanks so much!

      – Marsden Mars
      Nov 23 '18 at 20:32




      1




      1





      @Marius Try repeating the console.log(pop(array)) at the end of your snippet a few times, and then add a console.log(array) at the end, and see what it logs. Does the code do what the problem specification requires?

      – Michael Geary
      Nov 23 '18 at 23:39





      @Marius Try repeating the console.log(pop(array)) at the end of your snippet a few times, and then add a console.log(array) at the end, and see what it logs. Does the code do what the problem specification requires?

      – Michael Geary
      Nov 23 '18 at 23:39













      4














      A much simpler solution is to just decrease the length of the array by one. No need to create a second array.






      function pop (array){
      let last = array[array.length-1]; // Store last item in array
      array.length = array.length > 0 ? array.length - 1 : 0; // Decrease length
      return last; // Return last item
      }

      // Test function
      function logger(ary){
      console.log("Original array: " + ary.join(", "), "ntItem popped off: " + pop(ary), "ntArray contents now: " + ary.join(", "));
      }

      // Tests
      var ary = [1,2,3,4]; logger(ary);
      var ary = ["red", "white", "blue", "green"]; logger(ary);
      var ary = ["onlyItem"]; logger(ary);
      var ary = ; logger(ary);
      var ary = [false]; logger(ary);








      share|improve this answer





















      • 1





        @ScottMarcus just return last;

        – Thomas
        Nov 23 '18 at 20:34











      • @Thomas LOL, yeah. That works too!

        – Scott Marcus
        Nov 23 '18 at 20:35
















      4














      A much simpler solution is to just decrease the length of the array by one. No need to create a second array.






      function pop (array){
      let last = array[array.length-1]; // Store last item in array
      array.length = array.length > 0 ? array.length - 1 : 0; // Decrease length
      return last; // Return last item
      }

      // Test function
      function logger(ary){
      console.log("Original array: " + ary.join(", "), "ntItem popped off: " + pop(ary), "ntArray contents now: " + ary.join(", "));
      }

      // Tests
      var ary = [1,2,3,4]; logger(ary);
      var ary = ["red", "white", "blue", "green"]; logger(ary);
      var ary = ["onlyItem"]; logger(ary);
      var ary = ; logger(ary);
      var ary = [false]; logger(ary);








      share|improve this answer





















      • 1





        @ScottMarcus just return last;

        – Thomas
        Nov 23 '18 at 20:34











      • @Thomas LOL, yeah. That works too!

        – Scott Marcus
        Nov 23 '18 at 20:35














      4












      4








      4







      A much simpler solution is to just decrease the length of the array by one. No need to create a second array.






      function pop (array){
      let last = array[array.length-1]; // Store last item in array
      array.length = array.length > 0 ? array.length - 1 : 0; // Decrease length
      return last; // Return last item
      }

      // Test function
      function logger(ary){
      console.log("Original array: " + ary.join(", "), "ntItem popped off: " + pop(ary), "ntArray contents now: " + ary.join(", "));
      }

      // Tests
      var ary = [1,2,3,4]; logger(ary);
      var ary = ["red", "white", "blue", "green"]; logger(ary);
      var ary = ["onlyItem"]; logger(ary);
      var ary = ; logger(ary);
      var ary = [false]; logger(ary);








      share|improve this answer















      A much simpler solution is to just decrease the length of the array by one. No need to create a second array.






      function pop (array){
      let last = array[array.length-1]; // Store last item in array
      array.length = array.length > 0 ? array.length - 1 : 0; // Decrease length
      return last; // Return last item
      }

      // Test function
      function logger(ary){
      console.log("Original array: " + ary.join(", "), "ntItem popped off: " + pop(ary), "ntArray contents now: " + ary.join(", "));
      }

      // Tests
      var ary = [1,2,3,4]; logger(ary);
      var ary = ["red", "white", "blue", "green"]; logger(ary);
      var ary = ["onlyItem"]; logger(ary);
      var ary = ; logger(ary);
      var ary = [false]; logger(ary);








      function pop (array){
      let last = array[array.length-1]; // Store last item in array
      array.length = array.length > 0 ? array.length - 1 : 0; // Decrease length
      return last; // Return last item
      }

      // Test function
      function logger(ary){
      console.log("Original array: " + ary.join(", "), "ntItem popped off: " + pop(ary), "ntArray contents now: " + ary.join(", "));
      }

      // Tests
      var ary = [1,2,3,4]; logger(ary);
      var ary = ["red", "white", "blue", "green"]; logger(ary);
      var ary = ["onlyItem"]; logger(ary);
      var ary = ; logger(ary);
      var ary = [false]; logger(ary);





      function pop (array){
      let last = array[array.length-1]; // Store last item in array
      array.length = array.length > 0 ? array.length - 1 : 0; // Decrease length
      return last; // Return last item
      }

      // Test function
      function logger(ary){
      console.log("Original array: " + ary.join(", "), "ntItem popped off: " + pop(ary), "ntArray contents now: " + ary.join(", "));
      }

      // Tests
      var ary = [1,2,3,4]; logger(ary);
      var ary = ["red", "white", "blue", "green"]; logger(ary);
      var ary = ["onlyItem"]; logger(ary);
      var ary = ; logger(ary);
      var ary = [false]; logger(ary);






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 23 '18 at 20:43

























      answered Nov 23 '18 at 20:14









      Scott MarcusScott Marcus

      38.8k52036




      38.8k52036








      • 1





        @ScottMarcus just return last;

        – Thomas
        Nov 23 '18 at 20:34











      • @Thomas LOL, yeah. That works too!

        – Scott Marcus
        Nov 23 '18 at 20:35














      • 1





        @ScottMarcus just return last;

        – Thomas
        Nov 23 '18 at 20:34











      • @Thomas LOL, yeah. That works too!

        – Scott Marcus
        Nov 23 '18 at 20:35








      1




      1





      @ScottMarcus just return last;

      – Thomas
      Nov 23 '18 at 20:34





      @ScottMarcus just return last;

      – Thomas
      Nov 23 '18 at 20:34













      @Thomas LOL, yeah. That works too!

      – Scott Marcus
      Nov 23 '18 at 20:35





      @Thomas LOL, yeah. That works too!

      – Scott Marcus
      Nov 23 '18 at 20:35











      2














      It seems like simple is better in this case:






      const example = [1,2,3,4];

      function pop(arr) {
      return arr && arr.splice(-1)[0]
      }
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))

      // edge case: should it return undefined or should it throw?
      console.log(pop())








      share|improve this answer


























      • This is a really good take on the problem. Simple solution.

        – Marius
        Nov 24 '18 at 19:21











      • Thanks, i learnt something.

        – Marius
        Nov 24 '18 at 19:22
















      2














      It seems like simple is better in this case:






      const example = [1,2,3,4];

      function pop(arr) {
      return arr && arr.splice(-1)[0]
      }
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))

      // edge case: should it return undefined or should it throw?
      console.log(pop())








      share|improve this answer


























      • This is a really good take on the problem. Simple solution.

        – Marius
        Nov 24 '18 at 19:21











      • Thanks, i learnt something.

        – Marius
        Nov 24 '18 at 19:22














      2












      2








      2







      It seems like simple is better in this case:






      const example = [1,2,3,4];

      function pop(arr) {
      return arr && arr.splice(-1)[0]
      }
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))

      // edge case: should it return undefined or should it throw?
      console.log(pop())








      share|improve this answer















      It seems like simple is better in this case:






      const example = [1,2,3,4];

      function pop(arr) {
      return arr && arr.splice(-1)[0]
      }
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))

      // edge case: should it return undefined or should it throw?
      console.log(pop())








      const example = [1,2,3,4];

      function pop(arr) {
      return arr && arr.splice(-1)[0]
      }
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))

      // edge case: should it return undefined or should it throw?
      console.log(pop())





      const example = [1,2,3,4];

      function pop(arr) {
      return arr && arr.splice(-1)[0]
      }
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))
      console.log(pop(example))

      // edge case: should it return undefined or should it throw?
      console.log(pop())






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 23 '18 at 21:04

























      answered Nov 23 '18 at 20:31









      Mark MeyerMark Meyer

      38.4k33159




      38.4k33159













      • This is a really good take on the problem. Simple solution.

        – Marius
        Nov 24 '18 at 19:21











      • Thanks, i learnt something.

        – Marius
        Nov 24 '18 at 19:22



















      • This is a really good take on the problem. Simple solution.

        – Marius
        Nov 24 '18 at 19:21











      • Thanks, i learnt something.

        – Marius
        Nov 24 '18 at 19:22

















      This is a really good take on the problem. Simple solution.

      – Marius
      Nov 24 '18 at 19:21





      This is a really good take on the problem. Simple solution.

      – Marius
      Nov 24 '18 at 19:21













      Thanks, i learnt something.

      – Marius
      Nov 24 '18 at 19:22





      Thanks, i learnt something.

      – Marius
      Nov 24 '18 at 19:22











      0














      I think what you are looking for is Array.prototype.slice(). You can use the length property of the array to determine whether it is empty and then return the last entry using slice.






      const example = [1,2,3,4];
      const emptyExample = ;

      const pop = group => group.length > 0
      ? group.slice(group.length - 1)[0]
      : undefined;

      const answers = [ pop(example), pop(emptyExample) ];
      console.log(answers);





      Edit from comment



      Example should remove from the array while returning last entry so Array.prototype.splice is probably the better function here.






      const example = [1,2,3,4];
      const emptyExample = ;

      const pop = group => (Array.isArray(group) && group.length > 0)
      ? group.splice(group.length - 1, 1)[0]
      : undefined;

      const initialExample = [ ...example ];
      const answers = [
      pop(example),
      pop(emptyExample),
      { initialExample, updatedExample: example, emptyExample }
      ];
      console.log(answers);








      share|improve this answer






























        0














        I think what you are looking for is Array.prototype.slice(). You can use the length property of the array to determine whether it is empty and then return the last entry using slice.






        const example = [1,2,3,4];
        const emptyExample = ;

        const pop = group => group.length > 0
        ? group.slice(group.length - 1)[0]
        : undefined;

        const answers = [ pop(example), pop(emptyExample) ];
        console.log(answers);





        Edit from comment



        Example should remove from the array while returning last entry so Array.prototype.splice is probably the better function here.






        const example = [1,2,3,4];
        const emptyExample = ;

        const pop = group => (Array.isArray(group) && group.length > 0)
        ? group.splice(group.length - 1, 1)[0]
        : undefined;

        const initialExample = [ ...example ];
        const answers = [
        pop(example),
        pop(emptyExample),
        { initialExample, updatedExample: example, emptyExample }
        ];
        console.log(answers);








        share|improve this answer




























          0












          0








          0







          I think what you are looking for is Array.prototype.slice(). You can use the length property of the array to determine whether it is empty and then return the last entry using slice.






          const example = [1,2,3,4];
          const emptyExample = ;

          const pop = group => group.length > 0
          ? group.slice(group.length - 1)[0]
          : undefined;

          const answers = [ pop(example), pop(emptyExample) ];
          console.log(answers);





          Edit from comment



          Example should remove from the array while returning last entry so Array.prototype.splice is probably the better function here.






          const example = [1,2,3,4];
          const emptyExample = ;

          const pop = group => (Array.isArray(group) && group.length > 0)
          ? group.splice(group.length - 1, 1)[0]
          : undefined;

          const initialExample = [ ...example ];
          const answers = [
          pop(example),
          pop(emptyExample),
          { initialExample, updatedExample: example, emptyExample }
          ];
          console.log(answers);








          share|improve this answer















          I think what you are looking for is Array.prototype.slice(). You can use the length property of the array to determine whether it is empty and then return the last entry using slice.






          const example = [1,2,3,4];
          const emptyExample = ;

          const pop = group => group.length > 0
          ? group.slice(group.length - 1)[0]
          : undefined;

          const answers = [ pop(example), pop(emptyExample) ];
          console.log(answers);





          Edit from comment



          Example should remove from the array while returning last entry so Array.prototype.splice is probably the better function here.






          const example = [1,2,3,4];
          const emptyExample = ;

          const pop = group => (Array.isArray(group) && group.length > 0)
          ? group.splice(group.length - 1, 1)[0]
          : undefined;

          const initialExample = [ ...example ];
          const answers = [
          pop(example),
          pop(emptyExample),
          { initialExample, updatedExample: example, emptyExample }
          ];
          console.log(answers);








          const example = [1,2,3,4];
          const emptyExample = ;

          const pop = group => group.length > 0
          ? group.slice(group.length - 1)[0]
          : undefined;

          const answers = [ pop(example), pop(emptyExample) ];
          console.log(answers);





          const example = [1,2,3,4];
          const emptyExample = ;

          const pop = group => group.length > 0
          ? group.slice(group.length - 1)[0]
          : undefined;

          const answers = [ pop(example), pop(emptyExample) ];
          console.log(answers);





          const example = [1,2,3,4];
          const emptyExample = ;

          const pop = group => (Array.isArray(group) && group.length > 0)
          ? group.splice(group.length - 1, 1)[0]
          : undefined;

          const initialExample = [ ...example ];
          const answers = [
          pop(example),
          pop(emptyExample),
          { initialExample, updatedExample: example, emptyExample }
          ];
          console.log(answers);





          const example = [1,2,3,4];
          const emptyExample = ;

          const pop = group => (Array.isArray(group) && group.length > 0)
          ? group.splice(group.length - 1, 1)[0]
          : undefined;

          const initialExample = [ ...example ];
          const answers = [
          pop(example),
          pop(emptyExample),
          { initialExample, updatedExample: example, emptyExample }
          ];
          console.log(answers);






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 23 '18 at 20:46

























          answered Nov 23 '18 at 20:19









          D LowtherD Lowther

          1,3181414




          1,3181414























              0















              Array.prototype.splice(start[, deleteCount[, item1[, item2[, ...]]]])



              The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

              ...

              Return value: An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.



              - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice




              What this means is that so long as the input to the function is an instance of Array, we can call Array#splice(-1) to remove the last element. If there are no elements, this will return an empty array. Because we will always be getting either an array with one element or an empty array, we can access the first element using [0]. If the array is empty, this will be undefined.



              So, check that that input is an array, then return Array#splice(-1)[0] if it is or undefined if it is not.






              function pop(input) {
              let output;
              if(input instanceof Array) {
              output = input.splice(-1)[0]
              }
              return output
              }

              function test(input) {
              console.log({
              before: input && Array.from(input),
              popped: pop(input),
              after: input
              })
              return test
              }

              test( [ 1, 2, 3, 4 ] )( [ 1 ] )( [ ] )( )( [ , , , ] )








              share|improve this answer




























                0















                Array.prototype.splice(start[, deleteCount[, item1[, item2[, ...]]]])



                The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

                ...

                Return value: An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.



                - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice




                What this means is that so long as the input to the function is an instance of Array, we can call Array#splice(-1) to remove the last element. If there are no elements, this will return an empty array. Because we will always be getting either an array with one element or an empty array, we can access the first element using [0]. If the array is empty, this will be undefined.



                So, check that that input is an array, then return Array#splice(-1)[0] if it is or undefined if it is not.






                function pop(input) {
                let output;
                if(input instanceof Array) {
                output = input.splice(-1)[0]
                }
                return output
                }

                function test(input) {
                console.log({
                before: input && Array.from(input),
                popped: pop(input),
                after: input
                })
                return test
                }

                test( [ 1, 2, 3, 4 ] )( [ 1 ] )( [ ] )( )( [ , , , ] )








                share|improve this answer


























                  0












                  0








                  0








                  Array.prototype.splice(start[, deleteCount[, item1[, item2[, ...]]]])



                  The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

                  ...

                  Return value: An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.



                  - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice




                  What this means is that so long as the input to the function is an instance of Array, we can call Array#splice(-1) to remove the last element. If there are no elements, this will return an empty array. Because we will always be getting either an array with one element or an empty array, we can access the first element using [0]. If the array is empty, this will be undefined.



                  So, check that that input is an array, then return Array#splice(-1)[0] if it is or undefined if it is not.






                  function pop(input) {
                  let output;
                  if(input instanceof Array) {
                  output = input.splice(-1)[0]
                  }
                  return output
                  }

                  function test(input) {
                  console.log({
                  before: input && Array.from(input),
                  popped: pop(input),
                  after: input
                  })
                  return test
                  }

                  test( [ 1, 2, 3, 4 ] )( [ 1 ] )( [ ] )( )( [ , , , ] )








                  share|improve this answer














                  Array.prototype.splice(start[, deleteCount[, item1[, item2[, ...]]]])



                  The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

                  ...

                  Return value: An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.



                  - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice




                  What this means is that so long as the input to the function is an instance of Array, we can call Array#splice(-1) to remove the last element. If there are no elements, this will return an empty array. Because we will always be getting either an array with one element or an empty array, we can access the first element using [0]. If the array is empty, this will be undefined.



                  So, check that that input is an array, then return Array#splice(-1)[0] if it is or undefined if it is not.






                  function pop(input) {
                  let output;
                  if(input instanceof Array) {
                  output = input.splice(-1)[0]
                  }
                  return output
                  }

                  function test(input) {
                  console.log({
                  before: input && Array.from(input),
                  popped: pop(input),
                  after: input
                  })
                  return test
                  }

                  test( [ 1, 2, 3, 4 ] )( [ 1 ] )( [ ] )( )( [ , , , ] )








                  function pop(input) {
                  let output;
                  if(input instanceof Array) {
                  output = input.splice(-1)[0]
                  }
                  return output
                  }

                  function test(input) {
                  console.log({
                  before: input && Array.from(input),
                  popped: pop(input),
                  after: input
                  })
                  return test
                  }

                  test( [ 1, 2, 3, 4 ] )( [ 1 ] )( [ ] )( )( [ , , , ] )





                  function pop(input) {
                  let output;
                  if(input instanceof Array) {
                  output = input.splice(-1)[0]
                  }
                  return output
                  }

                  function test(input) {
                  console.log({
                  before: input && Array.from(input),
                  popped: pop(input),
                  after: input
                  })
                  return test
                  }

                  test( [ 1, 2, 3, 4 ] )( [ 1 ] )( [ ] )( )( [ , , , ] )






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 23 '18 at 20:46









                  Tiny GiantTiny Giant

                  13.4k64056




                  13.4k64056























                      -1














                      You could use Array.splice()



                      function pop(arr) {
                      return arr.splice(-1)[0];
                      }


                      This will delete the last item in the array and return it.






                      share|improve this answer


























                      • This is pretty close, but has a couple of problems. The parameter name is not spelled consistently in the code, and if that is fixed, the return value is not correct. (It's almost correct, but read the problem description again.)

                        – Michael Geary
                        Nov 24 '18 at 4:24
















                      -1














                      You could use Array.splice()



                      function pop(arr) {
                      return arr.splice(-1)[0];
                      }


                      This will delete the last item in the array and return it.






                      share|improve this answer


























                      • This is pretty close, but has a couple of problems. The parameter name is not spelled consistently in the code, and if that is fixed, the return value is not correct. (It's almost correct, but read the problem description again.)

                        – Michael Geary
                        Nov 24 '18 at 4:24














                      -1












                      -1








                      -1







                      You could use Array.splice()



                      function pop(arr) {
                      return arr.splice(-1)[0];
                      }


                      This will delete the last item in the array and return it.






                      share|improve this answer















                      You could use Array.splice()



                      function pop(arr) {
                      return arr.splice(-1)[0];
                      }


                      This will delete the last item in the array and return it.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 25 '18 at 17:06

























                      answered Nov 23 '18 at 20:19









                      oriontoriont

                      1239




                      1239













                      • This is pretty close, but has a couple of problems. The parameter name is not spelled consistently in the code, and if that is fixed, the return value is not correct. (It's almost correct, but read the problem description again.)

                        – Michael Geary
                        Nov 24 '18 at 4:24



















                      • This is pretty close, but has a couple of problems. The parameter name is not spelled consistently in the code, and if that is fixed, the return value is not correct. (It's almost correct, but read the problem description again.)

                        – Michael Geary
                        Nov 24 '18 at 4:24

















                      This is pretty close, but has a couple of problems. The parameter name is not spelled consistently in the code, and if that is fixed, the return value is not correct. (It's almost correct, but read the problem description again.)

                      – Michael Geary
                      Nov 24 '18 at 4:24





                      This is pretty close, but has a couple of problems. The parameter name is not spelled consistently in the code, and if that is fixed, the return value is not correct. (It's almost correct, but read the problem description again.)

                      – Michael Geary
                      Nov 24 '18 at 4:24


















                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53452458%2fpop-the-last-item-off-of-an-array-without-using-built-in-the-array-pop-functio%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      TypeError: fit_transform() missing 1 required positional argument: 'X'