升序和降序排序

时间:2020-01-27 00:18:42

标签: javascript sorting

我正在尝试根据array of objects属性对change进行排序。

下面是排序功能,strange part is the price when below 100没有正确排序。我希望按asc or desc的{​​{1}}顺序对对象数组进行排序。

change or name

2 个答案:

答案 0 :(得分:2)

您正在将值作为文本而不是数字进行比较。

const data = [{
    "id": 74368,
    "account": "Gerald Wehner",
    "change": "186.00"
  },
  {
    "id": 55998,
    "account": "Augusta Koelpin",
    "change": "277.00"
  },
  {
    "id": 3044,
    "account": "Austyn Bradtke",
    "change": "473.00"
  },
  {
    "id": 50305,
    "account": "Lesly Boyer",
    "change": "56.00"
  },
  {
    "id": 20324,
    "account": "Marietta Lynch",
    "change": "707.00"
  },
  {
    "id": 40233,
    "account": "Eriberto Haley",
    "change": "923.00"
  }
];

sort = (arr, field, order, cond) => {
  const fn = cond ?
    function(x) {
      return Number(cond(x[field]));
    } :
    function(x) {
      return Number(x[field]);
    };

  order = !order ? 1 : -1;

  return arr.sort(function(a, b) {
    return a = fn(a), b = fn(b), order * ((a > b) - (b > a));
  })
}

console.log(sort(data, 'change', true, false))

答案 1 :(得分:1)

请注意,对于诸如“ account”这样的字符串,此字符串将按名字,然后按姓氏排序:

const data=[{id:74368,account:"Gerald Wehner",change:"186.00"},{id:55998,account:"Augusta Koelpin",change:"277.00"},{id:3044,account:"Austyn Bradtke",change:"473.00"},{id:50305,account:"Lesly Boyer",change:"56.00"},{id:20324,account:"Marietta Lynch",change:"707.00"},{id:40233,account:"Eriberto Haley",change:"923.00"}]

function sortData(dir, prop){
    return data.sort((a,b) => {
        let x = dir === "ASC" ? a : b
        let y = dir === "ASC" ? b : a
    
        if(isNaN(data[0][prop])){
            return x[prop].localeCompare(y[prop])
        }else{
            return x[prop] - y[prop] 
        }
    })
}

console.log(sortData("ASC", "change"))

更新

为新格式添加了功能(请参见注释)

const data=[{id:74368,account:"Gerald Wehner",change:" GeraldWehner - 186"},{id:55998,account:"AugustaKoelpin",change:"AugustaKoelpin - 999"}]

function sortData(dir, prop){
    return data.sort((a,b) => {
        let x = dir === "ASC" ? a : b
        let y = dir === "ASC" ? b : a
    
        let exProp = data[0][prop]
        if(isNaN(exProp)){
            if( exProp.indexOf("-") > -1 && !isNaN( exProp.split("-")[1].trim() ) ){
                let xTest = x[prop].split("-")[1].trim()
                let yTest = y[prop].split("-")[1].trim()
                
                return xTest - yTest
            }
            
            return x[prop].localeCompare(y[prop])
        }else{
            return x[prop] - y[prop] 
        }
    })
}

console.log(sortData("ASC", "change"))