gpt4 book ai didi

javascript - 在javascript中对数组对象进行排序

转载 作者:行者123 更新时间:2023-11-30 11:36:11 25 4
gpt4 key购买 nike

我有一个包含多个对象的数组,例如:

var test = [
{size: "85A (UK 42A)"},
{size: "80A (UK 40A)"},
{size: "105F (UK 48F)"},
{size: "95E (UK 46E)"},
{size: "92C (UK 44C)"}
]

我想按如下尺寸排序。

var test = [
{size: "80A (UK 40A)"}
{size: "85A (UK 42A)"},
{size: "92C (UK 44C)"}
{size: "95E (UK 46E)"},
{size: "105F (UK 48F)"}
]

我用过这个但是它返回了下面的数组:

function sorting(json_object, key_to_sort_by) {
function sortByKey(a, b) {
var x = a[key_to_sort_by];
var y = b[key_to_sort_by];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

json_object.sort(sortByKey);
}


var test = [
{size: "105F (UK 48F)"},
{size: "80A (UK 40A)"}
{size: "85A (UK 42A)"},
{size: "92C (UK 44C)"}
{size: "95E (UK 46E)"}
]

最佳答案

如果你也喜欢用数字后面的字符排序,你也可以使用正则表达式来获取这个值。

var test = [{ size: "105F (UK 48F)" }, { size: "80A (UK 40A)" }, { size: "85A (UK  2A)" }, { size: "92C (UK 44C)" }, { size: "80B (UK 40B)" }, { size: "80C (UK 40C)" }, { size: "95E (UK 46E)" }];

test.sort(function (a, b) {
function getV(s) { return s.match(/^(\d+)(\w+)/); }
var aa = getV(a.size),
bb = getV(b.size);
return aa[1] - bb[1] || aa[2].localeCompare(bb[2]);
});

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

对于庞大的数据集,您可以使用 sorting with map , 因为

The compareFunction can be invoked multiple times per element within the array. Depending on the compareFunction's nature, this may yield a high overhead. The more work a compareFunction does and the more elements there are to sort, the wiser it may be to consider using a map for sorting. The idea is to walk the array once to extract the actual values used for sorting into a temporary array, sort the temporary array and then walk the temporary array to achieve the right order.

// the array to be sorted
var list = [{ size: "105F (UK 48F)" }, { size: "80A (UK 40A)" }, { size: "85A (UK 2A)" }, { size: "92C (UK 44C)" }, { size: "80B (UK 40B)" }, { size: "80C (UK 40C)" }, { size: "95E (UK 46E)" }];

// temporary array holds objects with position and sort-value
var mapped = list.map(function(el, i) {
var temp = el.size.match(/^(\d+)(\w+)/);
return { index: i, number: +temp[1], string: temp[2] || '' };
});

// sorting the mapped array containing the reduced values
mapped.sort(function(a, b) {
return a.number - b.number || a.string.localeCompare(b.string);
});

// container for the resulting order
var result = mapped.map(function(el){
return list[el.index];
});

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com