Solution

To remove last element from array in react js, use array.pop() method it will remove the last element of the array.

pop()

The pop() method removes the last element from an array and returns that value to the caller. If you call pop() on an empty array, it returns undefined.

Snippet

In this snippet, we will create an array and use the pop() method method to remove the last element of array.

const arr = ["aguidehub", "infinitbility", "sortoutcode"];

let popped = arr.pop();

console.log(popped); // "sortoutcode"
console.log(arr); //  ["aguidehub", "infinitbility"]

Example

In this example, we will remove the last element of array and print the rest array in console and page.

Let’s start coding…

import React, { useEffect, useState } from "react";
export default function App() {
  const [arr, setArr] = useState(["aguidehub", "infinitbility", "sortoutcode"]);

  useEffect(() => {
    removeLastElement();
  }, []);

  const removeLastElement = () => {
    let newArr = [...arr];
    newArr.pop();
    console.log(newArr);
    setArr(newArr);
  };

  return (
    <div className="App">
      <h1>{`Rest Array`}</h1>
      <p>{JSON.stringify(arr)}</p>
    </div>
  );
}

Output

profile

codesandbox