Skip to content

Instantly share code, notes, and snippets.

@AlexKratky
Created May 16, 2022 13:52
Show Gist options
  • Save AlexKratky/581d88f586292346854062fd3acdfce7 to your computer and use it in GitHub Desktop.
Save AlexKratky/581d88f586292346854062fd3acdfce7 to your computer and use it in GitHub Desktop.
Sort array of object for user (user related data first)
const userId = 28;
const res = [
{name: 'A', id: 1},
{name: 'A1', id: 1},
{name: 'A2', id: 1},
{name: 'A3', id: 1},
{name: 'B', id: 2},
{name: 'B1', id: 2},
{name: 'B2', id: 2},
{name: 'C', id: null},
{name: 'D', id: 28},
{name: 'D1', id: 28},
{name: 'D2', id: 28},
{name: 'E', id: 30},
{name: 'E1', id: 30},
{name: 'E2', id: 30},
];
res.sort((a, b) => {
if (a.id === userId && b.id === userId) return 0;
if (a.id === userId) return -1;
if (b.id === userId) return 1;
return 0;
});
console.log(res);
// [ { "name": "F", "id": 28 }, { "name": "F1", "id": 28 }, { "name": "F2", "id": 28 }, { "name": "A", "id": 1 }, { "name": "A1", "id": 1 }, { "name": "A2", "id": 1 }, { "name": "A3", "id": 1 }, { "name": "B", "id": 2 }, { "name": "B1", "id": 2 }, { "name": "B2", "id": 2 }, { "name": "C", "id": null }, { "name": "D", "id": 30 }, { "name": "D1", "id": 30 }, { "name": "D2", "id": 30 } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment