Reputation: 59
I have the following data:
planets: [
{
planetName: '1',
countries: [
{
countryName:'1';
population: 432,
worth: 65,
},
{
countryName:'2';
population: 9000,
worth: 10,
},
{
countryName:'3';
population: 80,
worth: 200,
}
],
},
{
planetName: '2',
countries: [
{
countryName:'1';
population: 80,
worth: 100,
},
{
countryName:'2';
population: 800,
worth: 1,
},
{
countryName:'3';
population: 88,
worth: 77,
}
],
},
],
I want to sort the countries in each planet with respect to population or worth and get the sorted data of the planets data
if i sort by population in desc order , i want data as :
planets: [
{
planetName: '1',
countries: [
{
countryName:'2';
population: 9000,
worth: 10,
},
{
countryName:'1';
population: 432,
worth: 65,
},
{
countryName:'3';
population: 80,
worth: 200,
},
],
},
{
planetName: '2',
countries: [
{
countryName:'2';
population: 800,
worth: 1,
},
{
countryName:'3';
population: 88,
worth: 77,
},
{
countryName:'1';
population: 80,
worth: 100,
},
],
},
],`
The order of the planets should remain the same, but the countries in each planet should sort according to the sort by option either by population or by worth
Any idea how can sort these. Perhaps lodash chain, map could help but I am not sure how to use it..
Upvotes: 0
Views: 63
Reputation: 192
In a react hook with a planets list as one of it's states you could get it sorted like this:
const [planets, setPlanets] = useState(initialPlanets);
const sort = () => {
const newPlanetList = [];
for(const planet of planets) {
const newPlanet = { ...planet, countries: [...planet.countries] };
newPlanet.countries.sort((a, b) => {
if(a.population == b.population) {
return a.worth - b.worth;
}
return a.population - b.population;
})
newPlanetList.push(newPlanet);
}
setPlanets(newPlanetList);
}
The sorting algorithm is quite simple, if the population is the same, compare planets by their worth, otherwise compare the worth. That way you'd get the list sorted by population primarily and among planets with the same population they'd be sorted by worth.
Important thing about React state updates in nested object is that you should always make sure the object reference you pass to the setState function is different than the current state, hence why I am making a copy of the array in this example instead of just calling planets.forEach(planet => planet.countries.sort(...))
, that just won't work.
Upvotes: 1