Reputation: 43
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
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
Reputation: 6887
I have altered your code.
If no data is present in the array return undefined.
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
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)
Upvotes: 4