Reputation: 23
i have data like
const data =[
{
name:'gacvuc',
pot1[
{
density:1
}
]
pot2[
{
density:2
}
]
}
.....
]
now i made a toggle in that do we wanna see pot1 density or pot2 density and made a table with that like this
<tablebody>
data.map(a,in)=>{
const show= toggleChoice === 0 ? a.pot1 : a.pot2;
}
return(
<tablecell>{a.name}</tablecell>
<tablecell>{show.density}</tablecell>
</tablebody>
);
now what i wanna do is i wanna sort by density in ascending or descending or search by it's name can anyone show me how to do that
Upvotes: 0
Views: 137
Reputation: 21
First, I would recommend taking a look at the format of your data and looking for mistakes.
To sort your data, you can simply use the built-in sort method and pass in a function that gives instructions on how to sort two different objects in your data.
data.sort(function(a, b) {
// you can define this based on your toggle variable
const pot = "pot1";
// densities of both object
const aDensity = a[pot][0].density;
const bDensity = b[pot][0].density;
// compare them and then return -1, 0, or 1 accordingly
if (aDensity == bDensity) { // if they are equal, return 0
return 0;
}
else if(aDensity > bDensity) { // > return 1
return 1;
}
else { // < return -1
return -1;
}
})
In this snippet, you get the densities of two arbitrary objects, a and b, and then return -1, 0, or 1 depending on the values of the density. In this example. I sorted them in ascending order, but if you want descending, you could swap the 1 for -1 and vice versa in the code.
Upvotes: 1