If the prop name in the array equals the random name, how can I sort to show them first?

As I mentioned in the title, I have a parameter that comes from the url and I have an array. If the name of the objects in this array and the parameter match, I want to show them first, then I can show the remaining data.

const {randomName} = useParams()
//randomName = "ASD"

//Example Object

const example = [{name:"bcd", size:32}, {name:"ASD", size:32} , {name:"ASD", size:32} , {name:"scd", size:32}, {name:"lgh", size:32} ]

example.map((x, index) => 
 <div> {x.name} {index} </div>
 )

//I want it rendered like this

ASD 1 
ASD 2
anyone 3
anyone 4
anyone 5
....





>Solution :

You have to sort the array

const randomName = "ASD"

const example = [{
  name: "bcd",
  size: 32
}, {
  name: "ASD",
  size: 32
}, {
  name: "ASD",
  size: 32
}, {
  name: "scd",
  size: 32
}, {
  name: "lgh",
  size: 32
}]

const result = [...example].sort((a, b) =>
  a.name === randomName ? -1 : b.name === randomName ? 1 : 0
).map((x, index) =>
  `<div> ${x.name} ${index} </div>`
)

console.log(result)

Leave a Reply