-2

I have two arrays one is contentOrder that basically is and array of ids and the other one is blocksContent that is and array of objects, i want order the second array using the order of the ids from the first array how can id do this.

contentOrder

contentOrder = [
    "de19b7c5-ff69-4fce-a38d-c6f0ee0d1eb5",
    "58f0dcfe-55d8-447d-87cc-fc00ec068407",
    "58f0dcfe-55d8-447d-87cc-fc00ec085407"
    ]

blocksContent

blocksContent= [
  {blockId: "58f0dcfe-55d8-447d-87cc-fc00ec068407", documentId: 298, chapterId: "4c26640a-bcda-4788-aee3-5c1508f70a67"},
  {blockId: "58f0dcfe-55d8-447d-87cc-fc00ec085407", documentId: 298, chapterId: "4c26640a-bcda-4788-aee3-5c1508f70a67"}
  {blockId: "de19b7c5-ff69-4fce-a38d-c6f0ee0d1eb5", documentId: 298, chapterId: "4c26640a-bcda-4788"}
]
Miguel Frias
  • 2,242
  • 7
  • 29
  • 48

2 Answers2

1

Use sort and indexOf functions.

var contentOrder = [
    "de19b7c5-ff69-4fce-a38d-c6f0ee0d1eb5",
    "58f0dcfe-55d8-447d-87cc-fc00ec068407",
    "58f0dcfe-55d8-447d-87cc-fc00ec085407"
    ]


var blocksContent= [
  {blockId: "58f0dcfe-55d8-447d-87cc-fc00ec068407", documentId: 298, chapterId: "4c26640a-bcda-4788-aee3-5c1508f70a67"},
  {blockId: "58f0dcfe-55d8-447d-87cc-fc00ec085407", documentId: 298, chapterId: "4c26640a-bcda-4788-aee3-5c1508f70a67"},
  {blockId: "de19b7c5-ff69-4fce-a38d-c6f0ee0d1eb5", documentId: 298, chapterId: "4c26640a-bcda-4788"}
]

blocksContent.sort((a, b) => contentOrder.indexOf(a.blockId) - contentOrder.indexOf(b.blockId));

console.log(blocksContent);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ele
  • 32,412
  • 7
  • 33
  • 72
0
let sortedContent = []

contentOrder.forEach((val) => {
  blocksContent.forEach((val1)=> {
    if(val == val1.blockId)
      sortedContent.push(val1)
  })
})
Akash
  • 3,872
  • 2
  • 25
  • 43