簡體   English   中英

Ramda JS 根據索引將數組划分為多個子數組

[英]Ramda JS partition array into multiple sub-arrays based on indices

我想獲取一個數組並將其拆分為基於另一個索引數組的子數組字典:

const arr = ["A", "B", "C", "D", "E"];
const indices = [0, 0, 1, 0, 3];
    
// Would like to do something like this:
R.split(indices, array) // { "0": ["A", "B", "D"], "1": ["C"], "3": ["E"] }

在 Ramda 中有一種優雅的方法可以做到這一點嗎?

使用R.zip將 arrays 組合成值/索引對數組。 按索引分組,然后僅從對中取值:

 const { pipe, zip, groupBy, last, map, head } = R const fn = pipe( zip, // combine the arrays to an array of value/indice pairs groupBy(last), // group by the indices map(map(head)) // take only the values from the pairs ) const arr = ["A", "B", "C", "D", "E"] const indices = [0, 0, 1, 0, 3] const result = fn(arr, indices) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

暫無
暫無

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

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