How to print an array of object from highest to lowest value

Viewed 71

I am trying to print the value from API data and currently, I am able to print it. Now, I would like to print in the order of highest values to lowest values. I would like to show the array data by the highest value to the lowest. But, I am having a tough time figuring out how to do this. Here is my code:

    const userPoints = [
       {
         name: "John",
         value: "50"
        },
       {
         name: "James",
         value: "70"
        },
      {
         name: "Sam",
         value: "30"
        },
      {
         name: "Jane",
         value: "35"
        },
    
    
    ]
    
    
    return (
       <>
    {userPoints.map((item, i)=>(
       <div key={i}>
          <h1>{item.name}</h1>
          <h1>{item.value}</h1>  
       </div>
    
    ))
    }

  </>

)

This is the order I want to print

enter image description here

2 Answers

This should do the trick:

const userPoints = [
  {
    name: "John",
    value: "50",
  },
  {
    name: "James",
    value: "70",
  },
  {
    name: "Sam",
    value: "30",
  },
  {
    name: "Jane",
    value: "35",
  },
];

userPoints.sort((a, b) => b.value - a.value);

console.log(userPoints);

All you need to do is to sort the array try this:

const userPoints = [
    {
      name: "John",
      value: "50",
    },
    {
      name: "James",
      value: "70",
    },
    {
      name: "Sam",
      value: "30",
    },
    {
      name: "Jane",
      value: "35",
    },
  ];

  return (
    <>
      {userPoints
        .sort((a, b) => b.value - a.value)
        .map((item, i) => (
          <div key={i} style={{ display: "flex" }}>
            <h1 style={{ marginRight: 3 }}>{i + 1}</h1>
            <h1 style={{ marginRight: 3 }}>{item.name}</h1>
            <h1 style={{ marginRight: 3 }}>{item.value}</h1>
          </div>
        ))}
    </>
  );

Never mind about styling Good Luck

Related