Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
}
like image 334
henok Avatar asked Sep 12 '25 04:09

henok


2 Answers

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 (...)

like image 161
hgb123 Avatar answered Sep 14 '25 18:09

hgb123


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).

like image 31
Gineet Mehta Avatar answered Sep 14 '25 19:09

Gineet Mehta