递归排序进行取值

需求:

一组数据为对象数组 [{}, {}, {}],每个对象里面有若干个字段(值为数字),按要求取最大的值。

取值规则:

先取第一个字段的最大值,若第一个字段的最大值有多个,则比较最大值所在对象的第二个字段,以此类推。。。

  const arr =[
    {
      one: 13000,
      two: 30,
      there: 7,
    },
    {
      one: 132000,
      two: 31,
      there: 8,
    },
    {
      one: 13000,
      two: 20,
      there: 5,
    }
  ]
  const keysList = ['one', 'two', 'there']
  let maxVal = ''
  
  function sortData(key, data, keysListIndex) {
    let hh = []
    data.sort((a, b) => {
      return a[key] - b[key]
    })
    data.map((item, index) => {
      if (item[key] === data[data.length - 1][key]) {
        hh.push(item)
      }
    })

    if (hh.length === 1 || keysListIndex === keysList.length - 1) {
      // 取值
      maxVal = hh[0][keysList[keysListIndex]]
      console.log('==========(输出值)========>>>', maxVal)
    } else {
      keysListIndex += 1
      sortData(keysList[keysListIndex], hh, keysListIndex)
    }
  }
  sortData(keysList[0], arr, 0)
  

你可能感兴趣的:(js)