CodingSparkles

Three Possible Ways to Removing First Item from Array

JavaScript
3 min read
September 05, 2021
Image by Bruno Germany from Pixabay

Removing an item from the list will be more useful, while working on the applications like appointment planner. Because we may need to remove the particular appointment from the list of appointments. In this article, we will explore three different methods of removing an item from the list.

Input Array

const books = [
    {
        name: 'FullStack React',
        author: 'Anthony Accomazzo, Nate Murray'
    },
    {
        name: 'Learning React: Functional Web Development with React and Redux',
        author: 'Alex Banks & Eve Porcello'
    },
    {
        name: 'The Road to React by Robin Wieruch',
        author: 'Robin Wieruch'
    },
    {
        name: 'Learn React Hooks by Daniel Bugl',
        author: 'Daniel Bugl'
    }
];

1) Using splice

  • The splice() method is adding/removing an item to/from an array and it returns the removed items. It changes the original array.
const removeFirstItem = () => {
    books.splice(0, 1);
    return books;
}

removeFirstItem();

Output

0: {name: "Learning React: Functional Web Development with React and Redux", author: "Alex Banks & Eve Porcello"}
1: {name: "The Road to React by Robin Wieruch", author: "Robin Wieruch"}
2: {name: "Learn React Hooks by Daniel Bugl", author: "Daniel Bugl"}

2) Using slice

  • The slice() method returns the selected elements in an array, as a new array object. The original array remains the same.
const removeFirstItem = () => {
    const alteredBooks = books.slice(1, books.length);
    return alteredBooks;
}

removeFirstItem();

Output

0: {name: "Learning React: Functional Web Development with React and Redux", author: "Alex Banks & Eve Porcello"}
1: {name: "The Road to React by Robin Wieruch", author: "Robin Wieruch"}
2: {name: "Learn React Hooks by Daniel Bugl", author: "Daniel Bugl"}

Note: By using the splice() and slice() method able to remove n number of items from an array by passing the corresponding (index) value as input.


3) Using shift

  • The shift() method removes the first item of an array. Removed item is the return value of this method. It changes the original array.
const removeFirstItem = () => {
    books.shift();
    return books;
}

removeFirstItem();

Output

0: {name: "Learning React: Functional Web Development with React and Redux", author: "Alex Banks & Eve Porcello"}
1: {name: "The Road to React by Robin Wieruch", author: "Robin Wieruch"}
2: {name: "Learn React Hooks by Daniel Bugl", author: "Daniel Bugl"}

Note: By using the shift() method can remove only one item (i.e. first item) from an array at a time.


Share: