-1

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"}
]
3
  • Have you tried something? Any attempt to show? Commented Feb 15, 2018 at 13:40
  • I can't believe that StackOverflow recommends to "Downvote and move on" instead of asking OP what they've tried O_o Seriously?? Commented Feb 15, 2018 at 13:41
  • @JeremyThille I didn't downvote and move on, but it's expcted that users are familiar with how asking a question works. A question like this one means the user didn't bother reading the guides or didn't care enough. Commented Feb 15, 2018 at 13:43

2 Answers 2

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; }

Sign up to request clarification or add additional context in comments.

4 Comments

indexOf would work too, without a callback.
@NinaScholz you're totally right!
@Ele Thanks so much for you help.
@MiguelAngelFrias you're welcome!
0
let sortedContent = []

contentOrder.forEach((val) => {
  blocksContent.forEach((val1)=> {
    if(val == val1.blockId)
      sortedContent.push(val1)
  })
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.