How to remove all element from array except first in javascript

I want to remove the entire element from the array, except the array element, to the 0th index

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

The output must be a

+6
source share
7 answers

You can set the length property for the array.

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

OR, use the splice(startIndex) method

 var input =['a','b','c','d','e','f']; input.splice(1) console.log(input); 
+14
source

This is the head function. tail also demonstrated as a free feature.

Note that you must use head and tail for arrays with 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'] 
+2
source
 array = [a,b,c,d,e,f]; remaining = array[0]; array = [remaining]; 
0
source

You can use splice to achieve this.

 Input.splice(0, 1); 

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

0
source

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

0
source

If you want to store it in an array , you can use slice or splice . Or run the wirst entry again.

 var Input = ["a","b","c","d","e","f"]; console.log( [Input[0]] ); console.log( Input.slice(0, 1) ); console.log( Input.splice(0, 1) ); 
0
source
 var output=Input[0] 

It prints the first element in case you want to filter under certain restrictions

 var Input = [ a, b, c, d, e, a, c, b, e ]; $( "div" ).text( Input.join( ", " ) ); Input = jQuery.grep(Input, function( n, i ) { return ( n !== c ); }); 
0
source

All Articles