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
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
Approach 1: Store the index of array elements into another array which need to be removed. Start a loop and run it to the number of elements in the array. Use splice() method to remove the element at a particular index.
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);
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 use splice to achieve this.
Input.splice(0, 1);
More details here . . .http://www.w3schools.com/jsref/jsref_splice.asp
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
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) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With