How to remove all element from array except the first one in javascript
This is the head
function. tail
is also demonstrated as a complimentary function.
Note, you should only use head
and tail
on arrays that have a known length of 1 or more.
// head :: [a] -> a
const head = ([x,...xs]) => x;
// tail :: [a] -> [a]
const tail = ([x,...xs]) => xs;
let input = ['a','b','c','d','e','f'];
console.log(head(input)); // => 'a'
console.log(tail(input)); // => ['b','c','d','e','f']
array = [a,b,c,d,e,f];
remaining = array[0];
array = [remaining];
You can set the length
property of the array.
var input = ['a','b','c','d','e','f'];
input.length = 1;
console.log(input);
OR, Use splice(startIndex)
method
var input = ['a','b','c','d','e','f'];
input.splice(1);
console.log(input);
OR use Array.slice method
var input = ['a','b','c','d','e','f'];
var output = input.slice(0, 1) // 0-startIndex, 1 - endIndex
console.log(output);