Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
array reverse dosen't effect

I try to sort my array to revers and I use the reverse() function but it doesn't affect to view. I must to change the file and save it then I can see the changes.

Items.js:

import { useState } from "react";

const Items = (props) => {
  const [myArray, setMyArray] = useState([
    {
      pId: 1,
      title: "P 1",
    },
    {
      pId: 2,
      title: "P 2",
    },
    {
      pId: 3,
      title: "P 3",
    },
    {
      pId: 4,
      title: "P 4",
    },
  ]);

const handleSort = () => {
    console.log("before", myArray);
    setTimeout(() => {
      setMyArray(myArray.reverse());
      console.log("after", myArray);
    }, 500);
  };

  return (
     <div>
      {myArray.map((a) => (
        <span key={a.pId} className="m-3">
          {a.title}
        </span>
      ))}
       <button onClick={handleSort}>reverse</button>
     </div>
  );

};

export default Items;

enter image description here enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are reversing an array of objects. use the spread operator to spread the elements of your array.

This should work fine.

  let myArray = [
    {
      pId: 1,
      title: "P 1",
    },
    {
      pId: 2,
      title: "P 2",
    },
    {
      pId: 3,
      title: "P 3",
    },
    {
      pId: 4,
      title: "P 4",
    }
  ]
console.log([...myArray].reverse());

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!