簡體   English   中英

鏈接數組對象中的數組以按其中一個數組排序

[英]Link arrays in an object of arrays to sort by one of the arrays

我有一個具有以下結構的對象:

let obj = {
    "foo": ["orange", "apple", "pear", "grape", "lime"],
    "bar": [12, 6, 18, 3, 22],
    "bat": ["a", "b", "c", "d", "e"]
};

我想按bar排序,但也要保留foobat相對於bar的順序,如下所示:

obj = {
    "foo": ["grape", "apple", "orange", "pear", "lime"],
    "bar": [3, 6, 12, 18, 22],
    "bat": ["d", "b", "a", "c", "e"]
};

有沒有一種整潔的方法可以做到這一點,或者我是否需要將其轉換為數組數組,按索引排序(例如, arr.sort((a,b) => a[1] - b[1]); ),並轉換回對象?

 const obj = { "foo": ["orange", "apple", "pear", "grape", "lime"], "bar": [12, 6, 18, 3, 22], "bat": ["a", "b", "c", "d", "e"] }; // get original indices of sorted bar const indices = obj.bar .map((value, index) => ({ value, index })) .sort(({ value: a }, { value: b }) => a - b) .map(({ index }) => index); // iterate over obj's values to reorder according to indices const res = Object.entries(obj) .reduce((acc, [key, value]) => ({ ...acc, [key]: indices.map(i => value[i]) }), {}); console.log(res);

您可以基於所有值創建一個臨時數組。 然后您可以根據bar對該數組進行排序。 排序后,只需在迭代時將數據填充到新響應即可。

 const obj = { foo: ["orange", "apple", "pear", "grape", "lime"], bar: [12, 6, 18, 3, 22], bat: ["a", "b", "c", "d", "e"], }; const arr = obj.bar .map((bar, index) => ({ bar, index, })) .sort((x, y) => x.bar - y.bar); console.log(arr); const res = arr.reduce( (map, { bar, index }, i) => { map.bar[i] = bar; map.foo[i] = obj.foo[index]; map.bat[i] = obj.bat[index]; return map; }, { foo: [], bar: [], bat: [] } ); console.log(res);

暫無
暫無

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

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