javascript - 根据键值对对象数组进行排序或排序

标签 javascript arrays sorting

<分区>

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

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

我想对数组进行排序,以便第一个值是带有“西类牙”的值,然后显示所有其他值。我试过 array.sort 但它似乎不起作用。不确定我做错了什么。

到目前为止我已经尝试过了

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

还有

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

最佳答案

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

其他国家排序不稳定。

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; }

关于javascript - 根据键值对对象数组进行排序或排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47858131/

相关文章:

javascript - 从 JSON 对象中选择项目并作为 JSON 对象返回,如 C# LINQ

python - 在 python 中将字节转换为 BufferedReader

c - C中数组相同元素

java - 如何从排序列表中获取第一个元素?

c# - 如何对通用列表中的部分项目进行排序

javascript - Style-Loader 可用功能在 Webpack 2.x 中不起作用

javascript - 在数组中搜索至少 1 个匹配项并返回 true

javascript - 如何使用 node-json2html 将 json 显示为 html?

java - 一维ArrayList基本统计计算器

c++ - 蛇形图案的排序点坐标