henok
henok

Reputation: 43

removes the first element in an array without using shift() method

In my software engineering boot camp prep course I was asked to write a a JavaScript function that removes the first value in an array and returns the value of the removed element without using the built-in shift method.

It should return undefined if the array is empty. My code looks like below, but it does not pass all the tests.

function shift(arr) {
    let arr1 = [];
    arr1 = arr.splice(0, 1);
    if (arr.length > 0) {
        return arr1;
    }
    return "undefined";
}

Upvotes: 4

Views: 4408

Answers (3)

Gineet Mehta
Gineet Mehta

Reputation: 56

Sounds like a good use case for the Array.splice method. Give it a read here.

This should be the solution you're looking for

function myShift(arr) {
    if (!arr || arr.length === 0) return undefined;
    return arr.splice(0, 1);
}

If the array passed to the method is falsy (null/undefined), or if it has 0 elements, return undefined.
The splice method will return the elements removed from the array.
Since you remove 1 element from the 0th index, it will return that element (and also mutate the original array).

Upvotes: 1

Alaksandar Jesus Gene
Alaksandar Jesus Gene

Reputation: 6887

I have altered your code.

  1. If no data is present in the array return undefined.

  2. If yes, return the first value by splice method.

function shift(arr) {
    if(!arr.length){
      return undefined;
    }
    arr1 = arr.splice(0, 1);
   return arr1
   }

var arr = [12,14,156];
console.log(shift(arr));

Upvotes: 0

hgb123
hgb123

Reputation: 14891

You could use destructing assignment combined with spread operator

const arr = [1, 2, 3]

const [removed, ...newArr] = arr

console.log(removed)
console.log(newArr)


Reference

Destructuring assignment

Spread syntax (...)

Upvotes: 4

Related Questions