簡體   English   中英

特殊排序對象數組

[英]Special sorting of an array of objects

因此,有大量關於此類排序的帖子:

var arr = [{a: 1}, {b: 2}]按字母順序排列,但是如果您有類似var arr = [{a: 100}, {a: 50}]東西,該怎么辦呢?說“哦,你是同一個人?讓我們按值對您進行排序(該值始終是數字)。

我不確定如何用lodash或任何其他類似的javascript方式進行操作。

最終結果應為:

[{b: 2}, {a: 1}] // Keys are different (alphabetical)
// or:
[{a: 50}, {a: 100}] // Keys are the same (lowest to highest)

我在堆棧溢出上看到的所有內容都變得一團糟(代碼明智),我當時在想,lodash上有排序方法,但是在這種情況下,我如何准確地實現所需的目標?

有任何想法嗎?

有人問了一個好問題,還有更多的鑰匙嗎? 他們只是ab嗎?

在任何給定時間,此數組中將只有兩個對象,是的,鍵只能是字符串,在這種情況下,字符串可以是貓,狗,鼠標,蘋果,香蕉等任何東西。

這些值將永遠只能是數字。

清除空氣

如果鍵匹配,則僅按值對數組排序;如果鍵不匹配,則僅按鍵對數組排序。 該數組中將永遠只有兩個對象。 對於誤解表示歉意。

如果對象中始終有一個屬性,則可以首先使用localeCompare key排序,然后按該屬性的值排序。

 var arr = [{b: 2}, {b: 10}, {a: 1}, {c: 1}, {a: 20}] arr.sort(function(a, b) { var kA = Object.keys(a)[0] var kB = Object.keys(b)[0] return kA.localeCompare(kB) || a[kA] - b[kB] }) console.log(arr) 

在排序之前,您可以創建唯一鍵數組,可用於通過檢查length是否大於1來檢查所有對象是否具有相同的鍵,並在sort函數中使用該鍵。

 var arr = [{b: 10}, {b: 2}, {a: 1}, {c: 1}, {a: 20}, {b: 22}] var arr2 = [{a: 10}, {a: 2}, {a: 1}, {a: 22}] function customSort(data) { var keys = [...new Set([].concat(...data.map(e => Object.keys(e))))] data.sort(function(a, b) { var kA = Object.keys(a)[0] var kB = Object.keys(b)[0] return keys.length > 1 ? kA.localeCompare(kB) : a[kA] - b[kB] }) return data; } console.log(customSort(arr)) console.log(customSort(arr2)) 

您只能使用一個函數來執行兩種類型的排序(適合您的情況,其中只有一個包含兩個項目的數組,但是對於數組長度而言,這是完全通用的):

 var arr1 = [{a: 30}, {a: 2}]; var arr2 = [{b: 30}, {a: 2}]; function sortArr(arr) { return arr.sort((a, b) => { var aKey = Object.keys(a)[0]; var bKey = Object.keys(b)[0]; return (aKey !== bKey) ? aKey.localeCompare(bKey) : a[aKey] - b[bKey]; }); } var sortedArr1 = sortArr(arr1); var sortedArr2 = sortArr(arr2); console.log(sortedArr1); console.log(sortedArr2); 

 var arr = [{b: 2}, {a: 1}, {b: 1}, {a: 100}, {a: 20}]; arr.sort(function(a, b) { var aKey = a.hasOwnProperty("a")? "a": "b", // get the first object key (if it has the property "a" then its key is "a", otherwise it's "b") bKey = b.hasOwnProperty("a")? "a": "b"; // same for the second object return aKey === bKey? // if the keys are equal a[aKey] - b[aKey]: // then sort the two objects by the value of that key (stored in either aKey or bKey) aKey.localeCompare(bKey); // otherwise sort by the strings aKey and bKey (the keys of the two objects) }); console.log(arr); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM