0
const myOldArr = [2, 3, 6];
const newArr = myOldArr.pop().shift();

Why does doing this give me a TypeError? Is there a way to do this without a loop? I want the new array to be stored inside a variable so the remaining numbers that don't get removed are stored inside an array of some sort.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • 1
    `pop` [returns the _element_ that you popped](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop). It is not an array that you can then use `shift` on. – Andy Oct 07 '19 at 10:52
  • Do not vandalize your posts. By posting on this site, you've irrevocably granted the Stack Exchange network the right to distribute that content under the [CC BY-SA 4.0 license](//creativecommons.org/licenses/by-sa/4.0/) for as long as it sees fit to do so. For alternatives to deletion, see: [I've thought better of my question; can I delete it?](https://stackoverflow.com/help/what-to-do-instead-of-deleting-question) – Cody Gray - on strike Jul 09 '21 at 05:46

2 Answers2

1

.pop() returns the last element form your array and so .shift() won't work,

If you want to keep the myOldArr and create a new one without the first and last element, you can do this by using .slice(1, -1):

const myOldArr = [2, 3, 6];
const myNewArr = myOldArr.slice(1, -1);
console.log(myNewArr);

Or, if you don't mind moifying the original array, you can do this by not chaining both methods:

const myOldArr = [2, 3, 6];
myOldArr.pop()
myOldArr.shift();
console.log(myOldArr);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

Use them separately

Array.pop() and Array.shift() will return a value of array your trying to use shift in number 6 so it will throw error

const myOldArr = [2, 3, 6];
myOldArr.pop();//last 
myOldArr.shift();//first
console.log(myOldArr)
Ravi Makwana
  • 2,782
  • 1
  • 29
  • 41
ellipsis
  • 12,049
  • 2
  • 17
  • 33