2017-03-03 40 views
2

我有以下代碼:數組排序 - 傳遞一個比較函數

var compare = function(nodeA, nodeB){ 
    return +nodeA.index - +nodeB.index; 
}; 

var sort = function(nodes){ 
    nodes.sort(compare); 
}; 

節點有這個(僞)結構:

{ 
    index: <integer> 
    value: <literal> 
} 

而且它目前對其進行排序的常規方式,當我所說的sort功能,並打印出每個節點的索引的:

0 
1 
2 
3 

我怎樣才能改變我的目前的邏輯,使其看起來像這樣? :

1 
2 
3 
0 <-- 0 should be considered the biggest index 
+0

的可能的複製[如何在JavaScript排序功能的工作,隨着比較功能(HTTP://計算器.COM /問題/ 6567941 /如何-做排序功能,工作在JavaScript的沿與-比較功能) –

回答

1

您可以零添加特殊處理:

var compare = function(nodeA, nodeB) { 
 
    // in case both sides are equal 
 
    if (nodeA.index === nodeB.index) { 
 
    return 0; 
 
    } 
 
    if (nodeA.index === 0) { 
 
    return 1; 
 
    } 
 
    if (nodeB.index === 0) { 
 
    return -1; 
 
    } 
 

 
    return +nodeA.index - +nodeB.index; 
 
}; 
 

 
var data = [{ 
 
    index: 2, 
 
    value: 'a' 
 
}, { 
 
    index: 0, 
 
    value: 'b' 
 
}, { 
 
    index: 3, 
 
    value: 'c' 
 
}, { 
 
    index: 1, 
 
    value: 'd' 
 
}] 
 

 
data.sort(compare); 
 

 
console.log(data);

1

您可以先按條件索引!= 0然後按索引值排序。

var data = [{ 
 
    index: 2, 
 
    value: 'a' 
 
}, { 
 
    index: 0, 
 
    value: 'b' 
 
},{ 
 
    index: 3, 
 
    value: 'c' 
 
},{ 
 
    index: 1, 
 
    value: 'd' 
 
}] 
 

 
var result = data.sort(function(a, b) { 
 
    return (b.index != 0) - (a.index != 0) || (a.index - b.index) 
 
}) 
 
console.log(result)

0

只要改變比較:

var compare = function(nodeA, nodeB){ 
    return ((+nodeA.index || Infinity) - (+nodeB.index || Infinity)) || Infinity; 
}; 

||運算符返回不是「falsy」的第一個值,這是「真值」值,但也是實際值。這是爲變量創建默認值的EMCA5「技巧」。

於是解釋:

  • 爲​​
  • nodeA.index > 0 && nodeB.index == 0 => somevalue - Infinity == -Infinity
  • nodeA.index == 0 && nodeB.index == 0 => Infinity - Infinity == NaN在這種情況下,|| Infinity選項choosen
0

你只需要改變你的比較功能一點點:

var compare = function(nodeA, nodeB){ 
    if (!+nodeA.index) return 1; 
    if (!+nodeB.index) return -1; 
    return +nodeA.index - +nodeB.index; 
};