'Typescript javascript : custom sort on object array [duplicate]

I am looking for a typescript code snippet to get a custom order of the object array, by listing objects in order by type fiction, romance, other, drama, comedy.

I've tried .find() and push(); .sort(); but did not feel that its the right way.

please advise

the above question doesn't solve my use case. stackoverflow.com/questions/6913512/… its not a straight sort. I need it to sort by custom order fiction romance, other, drama, comedy.

  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "type": "fiction",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "type": "drama",
    "completed": false
  },
  {
    "userId": 1,
    "id": 3,
    "title": "fugiat veniam minus",
    "type": "fiction",
    "completed": false
  },
  {
    "userId": 1,
    "id": 4,
    "title": "et porro tempora",
    "type": "comedy",
    "completed": true
  },
  {
    "userId": 1,
    "id": 5,
    "title": "laboriosam mollitia et enim quasi adipisci quia provident illum",
    "type": "fiction",
    "completed": false
  },
  {
    "userId": 1,
    "id": 6,
    "title": "qui ullam ratione quibusdam voluptatem quia omnis",
    "type": "romance",
    "completed": false
  },
  {
    "userId": 1,
    "id": 7,
    "title": "illo expedita consequatur quia in",
    "type": "other",
    "completed": false
  }```


Solution 1:[1]

You can do:

const data = [{userId: 1,id: 1,title: "delectus aut autem",type: "fiction",completed: false,},{userId: 1,id: 2,title: "quis ut nam facilis et officia qui",type: "drama",completed: false,},{userId: 1,id: 3,title: "fugiat veniam minus",type: "fiction",completed: false,},{userId: 1,id: 4,title: "et porro tempora",type: "comedy",completed: true,},{userId: 1,id: 5,title: "laboriosam mollitia et enim quasi adipisci quia provident illum",type: "fiction",completed: false,},{userId: 1,id: 6,title: "qui ullam ratione quibusdam voluptatem quia omnis",type: "romance",completed: false,},{userId: 1,id: 7,title: "illo expedita consequatur quia in",type: "other",completed: false}]

const order = ['fiction', 'romance', 'other', 'drama', 'comedy']
const dataHash = data.reduce((a, c) => {
  a[c.type] = a[c.type] || { array: [] }
  a[c.type].array.push(c)
  return a
}, {})
const result = order.map(o => dataHash[o].array).flat()

console.log(result)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1