程式語法JavaScriptJavaScript 陣列元素及 Object 順序重新排序 sort()

JavaScript 陣列元素順序重新排序 sort()

排序函數 sort() 方法,預設為 ASCII 字符順序進行「升序排列」。

陣列.sort()

var Brand = ["Oldsmobile", "Pontiac", "Buick", "Cadillac", "Holden", "Saturn", "GMC"];
Brand.sort()
Buick, Cadillac, GMC, Holden, Oldsmobile, Pontiac, Saturn

Brand.sort() //陣列重新排序
Brand.reverse() //順序反轉(反轉元素的排列秩序)
Saturn, Pontiac, Oldsmobile, Holden, GMC, Cadillac, Buick


數字陣列.sort(compare function 函數)

var InStock = [12, 3, 5, 53, 12, 53, 47];

數字陣列直接於 .sort() 預設下則是以 ASCII 字符順序。需要使用 function 函數來進行。

InStock.sort()
12, 12, 3, 47, 5, 53, 53

InStock.sort(function (a, b) {
  return a - b
});
3, 5, 12, 12, 47, 53, 53

InStock.sort(function (a, b) {
  return b - a //順序反轉
});
53, 53, 47, 12, 12, 5, 3

刪除重複的元素使用 forEach 函數來進行。IE9+
針對陣列中的每個元素各呼叫 callbackfn 函式一次(以遞增索引順序)。

var NewStock = [];
InStock.forEach(function (value) {
  if (NewStock.indexOf(value) == -1) {
    NewStock.push(value);
  }
});
3, 5, 12, 47, 53

JavaScript Object 排序

var Vehicles = [
{InStock:12, Brand:"Oldsmobile", Year:"2006-2008"},
{InStock:3, Brand:"Pontiac", Year:"2008-2010"},
{InStock:5, Brand:"Buick", Year:"2009-2010"},
{InStock:53, Brand:"Cadillac", Year:"2011-2013"},
{InStock:12, Brand:"Holden", Year:"2004-2006"},
{InStock:53, Brand:"Saturn", Year:"2009-2013"},
{InStock:47, Brand:"GMC", Year:"2007-2008"}
];

列出目前的值

for (var i = 0, l = Vehicles.length; i < l; ++i) {
 document.write(Vehicles[i].InStock + ", " +
 Vehicles[i].Brand + ", " +
 Vehicles[i].Year + "<br/>");
}
12, Oldsmobile, 2006-2008
3, Pontiac, 2008-2010
5, Buick, 2009-2010
53, Cadillac, 2011-2013
12, Holden, 2004-2006
53, Saturn, 2009-2013
47, GMC, 2007-2008

依照 Brand 進行順序。

Vehicles = Vehicles.sort(function (a, b) {
 return a.Brand > b.Brand ? 1 : -1;
});
5, Buick, 2009-2010
53, Cadillac, 2011-2013
47, GMC, 2007-2008
12, Holden, 2004-2006
12, Oldsmobile, 2006-2008
3, Pontiac, 2008-2010
53, Saturn, 2009-2013

依照 Year 進行順序(比較改用 a.Year < b.Year 由大到小)。

Vehicles = Vehicles.sort(function (a, b) {
 return a.Year < b.Year ? 1 : -1;
});
53, Cadillac, 2011-2013
53, Saturn, 2009-2013
5, Buick, 2009-2010
3, Pontiac, 2008-2010
47, GMC, 2007-2008
12, Oldsmobile, 2006-2008
12, Holden, 2004-2006

Modification in

回應文章

請先登入