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";
}
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";
}
Share
Improve this question
edited Aug 24, 2020 at 7:13
Jan Schultke
40.8k8 gold badges99 silver badges177 bronze badges
asked Aug 24, 2020 at 7:01
henokhenok
431 silver badge3 bronze badges
3
-
1
Are you sure you are supposed to return a string and not
undefined
if the array is empty? – UnholySheep Commented Aug 24, 2020 at 7:03 -
1
Also
arr1
is an array, but your requirement seems to be to return a single element, so that would bearr1[0]
– UnholySheep Commented Aug 24, 2020 at 7:04 -
Also you should check whether
arr
is empty before you try and splice a value out of it. – Nick Commented Aug 24, 2020 at 7:07
3 Answers
Reset to default 4You could use destructing assignment bined with spread operator
const arr = [1, 2, 3]
const [removed, ...newArr] = arr
console.log(removed)
console.log(newArr)
Reference
Destructuring assignment
Spread syntax (...)
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).
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));