按“宽 x 高”模式对数组进行排序

Sort arrays by "width x height" pattern

本文关键字:数组 排序 模式      更新时间:2023-09-26

>模式看起来像width x height

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

结果将是:

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

首先排序width然后排序height

通过使用.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
  }
});