Tag:arraylistobject
Article From:https://segmentfault.com/q/1010000012147871
Question:

Now there is an array

let arr = [
    {num: 3},
    {num: 4},
    {num: 1},
    {num: 2},
    {num: 0}
]

Is there any simple way to assign num in large to small order?level 1-5?

Finally, the data is obtained.

let arr = [
    {num: 4, level: 1},
    {num: 3, level: 2},
    {num: 2, level: 3},
    {num: 1, level: 4},
    {num: 0, level: 5}
]

I think a stupid thing is to use sort custom function to sort it first, then for loop, and to start assigning value to level from 1.

Is there a way to get it in place?

Answer 0:

One step in the wrong direction, level=5-num is handy and funny (I am also thinking like you, mark has waited for the big God).

Answer 1:
let arr = [
  { num: 3 },
  { num: 4 },
  { num: 1 },
  { num: 2 },
  { num: 0 },
]

const seq = arr
  .map(({ num }) => ({ num, level: arr.length - num }))
  .sort((objA, objB) => objA.level - objB.level)
console.log(seq)

I’m going to show up (a self mockery)

Leave a Reply

Your email address will not be published. Required fields are marked *