如何按字符串属性对对象数组进行排序
How to sort an array of objects by a string property
以以下内容为例:
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 Balan和Nina 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>
非常简单。谢谢大家
相关文章:
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- Javascript中的多维数组排序索引问题
- 如何按日期对Javascript对象数组排序
- 数组排序后显示更改
- 当许多元素相等时,Javascript数组排序无法正常工作
- Javascript数组排序速度受字符串长度的影响
- 按唯一键将对象数组排序为数组
- 以 js 为单位的数组排序
- js 数组排序无法正常工作
- 数组排序.论点从何而来
- 不需要的数组排序
- 数组排序不正确/不可预测,使用 indexOf 时
- Javascript将数组排序到树中
- 随后的多维数组排序会产生意外的结果
- 数组排序基于纯javascript搜索文本匹配
- Javascript自定义数组按数组排序
- 使用字符串按属性错误对对象进行数组排序
- 多维数组排序
- JavaScript与PHP在数组排序中的对比
- Javascript-关联数组排序