shift method
The shift
method removes the
first element from the array. In this
case, the original array is modified,
and the removed element is returned
as the result of the method.
Syntax
array.shift();
Example
Let's remove the first element from an array:
let arr = ['a', 'b', 'c', 'd', 'e'];
arr.shift();
console.log(arr);
The code execution result:
['b', 'c', 'd', 'e']
Example
Let's remove the first element from an array and display it on the screen:
let arr = ['a', 'b', 'c', 'd', 'e'];
let elem = arr.shift();
console.log(elem);
The code execution result:
'a'
Example . Usage
Let's convert an array into the string
'16-25-34'
. To solve the problem,
we use a combination of shift
,
pop
,
push
and join
methods:
let arr = ['1', '2', '3', '4', '5', '6'];
let res = [];
while (arr.length > 0) { // array is reduced in a loop until it reaches zero
let first = arr.shift();
let last = arr.pop();
let str = first + last; // there will be the string '16', then '25', then '34'
res.push(str);
}
// After the loop, res contains the array ['16', '25', '34']. We merge it into a string:
res = res.join('-');
console.log(res);
The code execution result:
'16-25-34'