【问题标题】:Javascript sort array of objects alphabetically AND put first objects with valueJavascript按字母顺序对对象数组进行排序并放置第一个具有值的对象
【发布时间】:2021-11-23 08:47:54
【问题描述】:

我正在尝试对包含各种对象数组的数据进行排序,myData 的 console.log 类似于:

[
  {
    name: 'Cdb',
    image: 'xxx',
    coll: 'xxx'
  },
  {
    name: 'Bcd',
    image: 'xxx',
    coll: 'xxx',
    url: 'myurl'
  }
]
[
  {
    name: 'Abc',
    image: 'xxx',
    coll: 'xxx'
  }
]

我正在尝试按字母顺序对其进行排序(基于 name 的值),如果 object 具有参数 url ,请将其放在开头。

所以输出将是:

    name: 'Cdb',
    image: 'xxx',
    coll: 'xxx',
    url: 'myurl'

    name: 'Abc',
    image: 'xxx',
    coll: 'xxx'

    name: 'Bcd',
    image: 'xxx',
    coll: 'xxx'

我尝试的是这个,以及它的许多变体,但它不起作用:

var myData = props?.data

console.log(props?.data)

if(props.data){
  // those with url first, then alphabetically
  myData = props.data.sort(function(a, b){
    return b.url? 1 || (a.name < b.name) : -1;
  })
}

【问题讨论】:

    标签: javascript arrays sorting object


    【解决方案1】:

    您可以使用!url 作为数字(0 或 1)并减去它们:

    const arr = [{"name":"Cdb","image":"xxx","coll":"xxx"},{"name":"Bcd","image":"xxx","coll":"xxx","url":"myurl"},{"name":"Abc","image":"xxx","coll":"xxx"}]
    
    arr.sort((a, b) => !a.url - !b.url || a.name.localeCompare(b.name));
      
    console.log(arr)

    这就是说,如果两者中恰好有一个具有url 参数,则应该首先出现。否则(如果两者都有,或者都没有),那么name 是决定性的。

    这样,当多个对象有url参数时,它们之间也将按name排序。

    【讨论】:

      猜你喜欢
      • 2019-06-15
      • 2021-02-18
      • 2014-12-30
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 2021-04-23
      相关资源
      最近更新 更多