gpt4 book ai didi

javascript - 按 "width x height"模式对数组进行排序

转载 作者:行者123 更新时间:2023-12-02 18:07:08 25 4
gpt4 key购买 nike

图案看起来像宽度x高度

var formats = [
"900x100",
"900x200",
"1200x200",
"1200x100",
"1100x100",
"1100x200"
];

结果将是:

"1200x200",
"1200x100",
"1100x200",
"1100x100",
"900x200",
"900x100"

首先排序宽度,然后排序高度

通过使用.sort()

formats.sort(function(a,b){
// do something
});

演示: http://jsbin.com/oGEroJI/1/edit?js,console

最佳答案

给你:

http://jsbin.com/oGEroJI/3/edit?js,console

formats.sort(function(a,b){
var a = a.split("x");
var b = b.split("x");
if (a[0] !== b[0]) {
return b[0] - a[0]; // by width
} else {
return b[1] - a[1]; // by height
}
});

关于javascript - 按 "width x height"模式对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20000975/

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