Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptDelete the first element of array without using shift() method in JavaScript

Delete the first element of array without using shift() method in JavaScript

Given an array containing some array elements and the task is to remove the first element from the array and thus reduce the size by 1. We are going to perform shift() method operation without actually using it with the help of JavaScript.

There are two approaches that are discussed below: 

Method 1: Using splice() Method

We can use the splice() method that is used to get the part of the array.

Example: In this example, we will implement the above approach.

Javascript




let Arr = ['Geeks', 'GFG', 'Geek', 'GeeksForGeeks'];
 
console.log("Array: [" + Arr + "]");
 
function myGFG() {
    Arr.splice(0, 1);
    console.log("Elements of Array: [" + Arr + "]");
}
 
myGFG();


Output

Array: [Geeks,GFG,Geek,GeeksForGeeks]
Elements of Array: [GFG,Geek,GeeksForGeeks]

Method 2: Using filter() Method

We can use the filter() method to filter out the element at index 0.

Example: In this example, we will implement the above approach.

Javascript




let Arr = ['Geeks', 'GFG', 'Geek', 'GeeksForGeeks'];
 
console.log("Array: [" + Arr + "]");
 
function removeFirst(element, index) {
    return index > 0;
}
 
function myGFG() {
    Arr = Arr.filter(removeFirst);
    console.log("Elements of array = [" + Arr + "]");
}
 
myGFG();


Output

Array: [Geeks,GFG,Geek,GeeksForGeeks]
Elements of array = [GFG,Geek,GeeksForGeeks]
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments