0

I have listOfChapters(see in below code) now this array title I print using map so that is print like this chapter1, chapter2, chapter-3, chapter -4 but i want to print in the sequence of weight how to possible this ?

                                                                 weight
listOfChapters.map(x => x.title) // current output is chapter-1    1
                                                      chapter-2    3
                                                      chapter-3    2
                                                      chapter-4    0

            // Exprected output using weight sequence chapter-4    0
                                                      chapter-1    1
                                                      chapter-3    2
                                                      chapter-2    3
listOfChapters = [
    0: {id: 242, title: "Chapter - 1", weight: 1}
    1: {id: 261, title: "Chapter - 2", weight: 3}
    2: {id: 262, title: "Chapter - 3", weight: 2}
    3: {id: 263, title: "chapter - 4", weight: 0}
]
0

2 Answers 2

0

Try this

listOfChapters.sort((a,b)=>a.weight-b.weight).map(p=>p.title)

listOfChapters.sort((a,b)=>a.weight-b.weight) will sort your array (mutate) in ascending order by weight

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

2 Comments

This code may work, but there is no explanation as to why it works. Consider providing one so it can help others understand what it does. It also isn't advised to answer on questions that have been marked as duplicate, unless your answer provides something other than the answers in the linked duplicate.
@Kobe good point... the question was answered before it was marked duplicate
0

Use below code

listOfChapters.sort((a,b)=>a.weight - b.weight)

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.