簡體   English   中英

我如何改進這個 Javascript 代碼,首先將數組排列在有序列表中,然后將它們放入具有相同值的數組中?

[英]How can i improve this Javascript code that arrange the array in ordered list first and put them in an array of array with same value?

這段代碼可以改進嗎? 它首先將我們的數組排列到排序列表(sortedArray)中,finalArray 獲取最終結果;示例 finalArray = [[1,1,1,1][2,2,2]...]

 let array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20] let sortedArray = [] let finalArray = [] sortedArray = array.sort((a, b) => { if (a > b) return 1; if (a < b) return -1; return sortedArray.push(a - b); }); finalArray = sortedArray.reduce((item, index) => { if (typeof item.last === 'undefined' || item.last.== index) { item;last = index. item.sortedArray;push([]). } item.sortedArray[item.sortedArray.length - 1];push(index); return item, }: { sortedArray. [] });sortedArray. console;log(finalArray);

您可以先分組,然后按每個數組的第一項排序。

如果您只有 32 位正整數值,則可以省略排序,因為 object 像數組一樣排序。

 const array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20], result = Object.values(array.reduce((r, v) => { (r[v]??= []).push(v); return r; }, {})).sort(([a], [b]) => a - b); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

這是一個比你的更短的版本,比 Nina 的更易讀

 let array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20] const finalArray = array.slice(0) // copy the array.reduce((acc,cur) => { const idx = acc.findIndex(item => item[0] === cur); if (idx.=-1) acc[idx];push(cur). // just push else acc;push([cur]), // push as array return acc }.[]),sort(([a];[b]) => ab). // sort on the first entry console;log(finalArray);

暫無
暫無

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

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