如何按字符串属性对对象数组进行排序

How to sort an array of objects by a string property

本文关键字:数组 排序 对象 何按 字符串 属性      更新时间:2023-09-26

以以下内容为例:

var data = [
{ name: 'Random 100 Index' },
{ name: 'Random 25 Index' },
{ name: 'Random 75 Index' },
{ name: 'Random 50 Index' } ];

我想根据name属性按升序排序这个数组。我用jQuery尝试了各种技术。我没有得到我想要的。问题是随机100索引将是排序数组中的第一项。以这个函数为例:

function sortByProperty(property) {
'use strict';
return function (a, b) {
    var sortStatus = 0;
    if (a[property] < b[property]) {
        sortStatus = -1;
    } else if (a[property] > b[property]) {
        sortStatus = 1;
    } 
    return sortStatus;
}; }

当我做var result = data.sort(sortByProperty('name'));时,结果如下:

[{ name: 'Random 100 Index' }, { name: 'Random 25 Index }, { name: 'Random 50 Index' }, { name: 'Random 75 Index' } ]

各项已正确排序,除了随机100索引应为最后一项。

如何解决这个问题?如何对这样的字符串数组排序?

您可以使用 sort() match() 。使用 match() 查找字符串中的整数值,在此基础上使用 sort() 对数组进行排序。

var data = [{
  name: 'Random 100 Index'
}, {
  name: 'Random 25 Index'
}, {
  name: 'Random 75 Index'
}, {
  name: 'Random 50 Index'
}];
var res = data.sort(function(a, b) {
  return a.name.match(/'d+/)[0] - b.name.match(/'d+/)[0];
});
document.write('<pre>' + JSON.stringify(res,null,2) + '</pre>');

UPDATE:它只会根据字符串中第一次出现的数字进行排序。

大型数据集索引值临时存储的结果

var data = [
        { name: 'Random 100 Index' },
        { name: 'Random 25 Index' },
        { name: 'Random 75 Index' },
        { name: 'Random 50 Index' }
    ],
    result = data.map(function (el, i) {
        return {
            index: i,
            value: /'d+/.exec(el.name)[0]
        };
    }).sort(function (a, b) {
        return a.value - b.value;
    }).map(function (el) {
        return data[el.index];
    });
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

感谢Pranav C BalanNina Scholz我想出了以下解决方案。

按字母顺序排序数组:

function sortByProperty(property) {
    'use strict';
    return function (a, b) {
        var sortStatus = 0;
        if (a[property] < b[property]) {
            sortStatus = -1;
        } else if (a[property] > b[property]) {
            sortStatus = 1;
        }
 
        return sortStatus;
    };
}
var result = data.sort(sortByProperty('name'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

并根据在属性文本中找到的第一个数字对数组进行排序:

var res2 = res1.sort(function(a, b) {
    return a.name.match(/'d+/)[0] - b.name.match(/'d+/)[0];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

非常简单。谢谢大家