shadowhunter_077
shadowhunter_077

Reputation: 494

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

Upvotes: 42

Views: 87700

Answers (9)

Jesus Tello
Jesus Tello

Reputation: 1

The shift() method is a perfect choice to do this.

var input = ['a','b','c','d','e','f'];  
let firstValue = input.shift();
console.log(firstValue);

Upvotes: 0

Satpal
Satpal

Reputation: 133403

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

Upvotes: 98

Evan Grillo
Evan Grillo

Reputation: 11

var input = ["a", "b", "c", "d", "e", "f"];

[input[0]];

// ["a"]

Upvotes: 0

Mulan
Mulan

Reputation: 135227

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']

Upvotes: 5

Parthasarathy
Parthasarathy

Reputation: 318

var output=Input[0]

It prints the first element in case of you want to filter under some constrains

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

Upvotes: -2

eisbehr
eisbehr

Reputation: 12452

If you want to keep it in an array, you can use slice or splice. Or wrap 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) );

Upvotes: 1

Mike Scotty
Mike Scotty

Reputation: 10782

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

Upvotes: 1

Ravikiran kalal
Ravikiran kalal

Reputation: 1070

You can use splice to achieve this.

Input.splice(0, 1);

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

Upvotes: 2

Prateik Darji
Prateik Darji

Reputation: 2317

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

Upvotes: 1

Related Questions