根据键值排序或排序对象数组[重复]

问题描述 投票:1回答:3

这个问题在这里已有答案:

我有一个包含对象的数组,每个对象都有以下属性:

{ country: 'United States' },
{ country: 'Netherlands' },
{ country: 'Spain' },
{ country: 'Spain' },

我想对数组进行排序,以便第一个值为'Spain',然后显示所有其他值。我尝试使用array.sort但似乎无法正常工作。不确定我做错了什么。

到目前为止,我试过这个

arr.sort(function(a, b) {return a.country === 'Spain'})

arr.sort(function(a, b) {if (a.country === 'Spain') {return 1}})
javascript arrays sorting
3个回答
3
投票

您可以使用字符串进行检查,您希望排序到顶部并获取比较的增量。

其他国家的排序顺序并不稳定。

var array = [{ country: 'United States' }, { country: 'Netherlands' }, { country: 'Spain' }, { country: 'Spain' }];

array.sort(function (a, b) {
    return (b.country === 'Spain') - (a.country === 'Spain');
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

对于稳定排序,将'Spain'排序到顶部,其余按原始索引排序,您可以使用sorting with map

var array = [{ country: 'United States' }, { country: 'Netherlands' }, { country: 'Spain' }, { country: 'Spain' }],
    sorted = array
        .map(function (o, i) {
            return { top: o.country === 'Spain', index: i };
        })
        .sort(function (a, b) {
            return b.top - a.top || a.index - b.index;
        })
        .map(function (o) {
            return array[o.index];
        });

console.log(sorted);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1
投票

这应该很容易使用Javascript数组函数,特别是sort()filter()reverse()

var json = [
  {
    country: 'United States'
  },
  {
    country: 'Netherlands'
  },
  {
    country: 'Spain'
  },
  {
    country: 'Spain'
  }
];

var sorted = 
  // Spain Terms First
  json.filter(j => j.country === 'Spain')
  // Add Alphabetically-Sorted Other Terms
  .concat(json.filter(j => j.country !== 'Spain').sort().reverse()); 
  
console.log(sorted);

1
投票

不需要实际排序。将它分成两个不同的数组,然后将它们组合起来。

这也保证了原始的子订单得以维持。

var data = [{"country":"United States"},{"country":"Netherlands"},{"country":"Spain"},{"country":"Spain"}];

var res = [].concat(...data.reduce((res, obj) =>
  (res[obj.country === "Spain" ? 0 : 1].push(obj), res)
, [[],[]]));

console.log(res);

如果你需要改变原作,那么这样做:

var data = [{"country":"United States"},{"country":"Netherlands"},{"country":"Spain"},{"country":"Spain"}];

var res = Object.assign(data, [].concat(...data.reduce((res, obj) =>
  (res[obj.country === "Spain" ? 0 : 1].push(obj), res)
, [[],[]])));

console.log(data);
© www.soinside.com 2019 - 2024. All rights reserved.