How can I sort the allGames array sorted to have the installedGames first?
const allGames = [
{ id: 2, name: 'game2' },
{ id: 1, name: 'game1' },
{ id: 4, name: 'game4' },
{ id: 3, name: 'game3' },
]
const installedGames = [
{ id: 2, name: 'game2' },
{ id: 3, name: 'game3' }
]
const sorted = allGames.sort((a, b) => {
return a.id - b.id // but this just sorts by id
});
Basically I want to get this order:
{ id: 2, name: 'game2' },
{ id: 3, name: 'game3' },
{ id: 1, name: 'game1' },
{ id: 4, name: 'game4' }
let allGames = [
{ id: 2, name: 'game2' },
{ id: 1, name: 'game1' },
{ id: 4, name: 'game4' },
{ id: 3, name: 'game3' },
]
let installedGames = [
{ id: 3, name: 'game3' },
{ id: 2, name: 'game2' },
]
// Step 1. sort both arrays
allGames = allGames.sort( (a,b) => a.id - b.id )
installedGames = installedGames.sort( (a,b) => a.id - b.id )
// Step 2. remove installedGames from allGames
const remainingGames = allGames.filter( game => !installedGames.find(g => g.name === game.name) )
// step 3. concatenate both
const sortedGames = installedGames.concat(remainingGames)
console.log(sortedGames)
Also, I'd suggest a model change. Instead of having two distinct arrays, I suggest having only one, and add an installed
attribute to your games. This will make your life easier :
const allGames = [
{ id: 2, name: 'game2', installed : true },
{ id: 1, name: 'game1', installed : false },
{ id: 4, name: 'game4', installed : false },
{ id: 3, name: 'game3', installed : true },
]
const sortedGames = allGames.sort((a, b) =>
+b.installed - +a.installed || a.id - b.id
);
console.log(sortedGames)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With