Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an array sorted based on the content of another array

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' }
like image 499
Cristian Muscalu Avatar asked Nov 28 '22 21:11

Cristian Muscalu


1 Answers

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)
like image 69
Jeremy Thille Avatar answered Mar 16 '23 20:03

Jeremy Thille