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}
]
Dharmesh
  • 5,383
  • 17
  • 46
  • 62

2 Answers2

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

Bill Cheng
  • 926
  • 7
  • 9
  • 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 Jul 25 '19 at 13:32
  • @Kobe good point... the question was answered before it was marked duplicate – Bill Cheng Jul 25 '19 at 13:33
0

Use below code

listOfChapters.sort((a,b)=>a.weight - b.weight)
ajaykumar mp
  • 487
  • 5
  • 12