The array of objects is sorted according to the property value from smallest to largest

function sortArray(prop) {
  return function(obj_1, obj_2) {
    let value_1 = obj_1[prop]
    let value_2 = obj_2[prop]

    return value_1 - value_2
  }
}

 

let arr = [
  {
    name: 'one',
    num: 99,
  },
  {
    name: 'two',
    num: 108,
  },
  {
    name: 'three',
    num: -1,
  },
  {
    name: 'four',
    num: 3,
  }
]

arr = arr.sort (sortArray ('num'))

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324817148&siteId=291194637