freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-an.../basic-data-structures/remove-items-from-an-array-...

2.9 KiB

id title challengeType
587d78b2367417b2b2512b0f Remove Items from an Array with pop() and shift() 1

Description

Both push() and unshift() have corresponding methods that are nearly functional opposites: pop() and shift(). As you may have guessed by now, instead of adding, pop() removes an element from the end of an array, while shift() removes an element from the beginning. The key difference between pop() and shift() and their cousins push() and unshift(), is that neither method takes parameters, and each only allows an array to be modified by a single element at a time. Let's take a look:
let greetings = ['whats up?', 'hello', 'see ya!'];

greetings.pop();
// now equals ['whats up?', 'hello']

greetings.shift();
// now equals ['hello']
We can also return the value of the removed element with either method like this:
let popped = greetings.pop();
// returns 'hello'
// greetings now equals []

Instructions

We have defined a function, popShift, which takes an array as an argument and returns a new array. Modify the function, using pop() and shift(), to remove the first and last elements of the argument array, and assign the removed elements to their corresponding variables, so that the returned array contains their values.

Tests

tests:
  - text: <code>popShift(["challenge", "is", "not", "complete"])</code> should return <code>["challenge", "complete"]</code>
    testString: assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), ["challenge", "complete"], '<code>popShift(["challenge", "is", "not", "complete"])</code> should return <code>["challenge", "complete"]</code>');
  - text: The <code>popShift</code> function should utilize the <code>pop()</code> method
    testString: assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1, 'The <code>popShift</code> function should utilize the <code>pop()</code> method');
  - text: The <code>popShift</code> function should utilize the <code>shift()</code> method
    testString: assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1, 'The <code>popShift</code> function should utilize the <code>shift()</code> method');

Challenge Seed

function popShift(arr) {
  let popped; // change this line
  let shifted; // change this line
  return [shifted, popped];
}

// do not change code below this line
console.log(popShift(['challenge', 'is', 'not', 'complete']));

Solution

// solution required