How to remove all element from array except the first one in javascript

shadowhunter_077 picture shadowhunter_077 · Sep 15, 2016 · Viewed 47.3k times · Source

I want to remove all element from array except the element of array at 0th index

["a", "b", "c", "d", "e", "f"]

Output should be a

Answer

Satpal picture Satpal · Sep 15, 2016

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