javascriptarraysslicearray-splice

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

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