Javascript sort an array based on another array

Posted on February 10, 2022

Data array

var dataArray = [
    { name: 'Alberta Owen', id: 1 },
    { name: 'Jimmy Murphy', id: 2 },
    { name: 'Jerald Roberson', id: 3 },
    { name: 'Roosevelt Douglas', id: 4 },
    { name: 'Mark Ramsey', id: 5 }
]

Sort array

var sortArray = ['Mark Ramsey', 'Jimmy Murphy', 'Alberta Owen'];

Sorting

dataArray.sort((a, b) => sortArray.indexOf(a) - sortArray.indexOf(b));
to join this conversation on Samprix.Already have an account? Sign in to comment
SPONSORS