Skip to content Skip to sidebar Skip to footer

How To Remove All Element From Array Except The First One In Javascript

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

Solution 1:

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 - endIndexconsole.log(output); 

Solution 2:

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] -> aconsthead = ([x,...xs]) => x;

// tail :: [a] -> [a]consttail = ([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']

Solution 3:

array = [a,b,c,d,e,f];remaining = array[0];array = [remaining];

Solution 4:

You can use splice to achieve this.

Input.splice(0, 1);

More details here . . .http://www.w3schools.com/jsref/jsref_splice.asp

Solution 5:

You can use slice:

var input =['a','b','c','d','e','f'];  
input = input.slice(0,1);
console.log(input);

Documentation: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Post a Comment for "How To Remove All Element From Array Except The First One In Javascript"