我正在尋找一種優雅的方式(最好是不可變的,lodash - 好的)來有條件地壓縮陣列。我想檢查section和path值組合的重復項,并附加ids這些重復項。所以給定
const arrayToBeCompacted = [
{
section: "Section name 1",
path: ["segment1", "segment2"],
ids: ["id1"]
},
{
section: "Section name 1",
path: ["segment1", "segment2"],
ids: ["id2"]
},
{
section: "Section name2",
path: ["segment1", "segment2"],
ids: ["id3"]
},
{
section: "Another section",
path: ["segment1", "segment2"],
ids: ["id4"]
},
{
section: "Another section",
path: ["segment1", "segment2"],
ids: ["id5"]
},
]
結果我想
const resultingArray = [
{
section: "Section name 1",
path: ["segment1", "segment2"],
ids: ["id1", "id2"]
},
{
section: "Section name 2",
path: ["segment1", "segment2"],
ids: ["id3"]
},
{
section: "Another section",
path: ["segment1", "segment2"],
ids: ["id4", "id5"]
},
]
似乎這并不是我想要的lodash.uniq(By, With)。lodash.union(By, With)
uj5u.com熱心網友回復:
你可以用減少來做到這一點
const arrayToBeCompacted = [
{
section: "Section name 1",
path: ["segment1", "segment2"],
ids: ["id1"]
},
{
section: "Section name 1",
path: ["segment1", "segment2"],
ids: ["id2"]
},
{
section: "Section name2",
path: ["segment1", "segment2"],
ids: ["id3"]
},
{
section: "Another section",
path: ["segment1", "segment2"],
ids: ["id4"]
},
{
section: "Another section",
path: ["segment1", "segment2"],
ids: ["id5"]
},
]
const compacted = Object.values(arrayToBeCompacted.reduce((res, {section, path, ids}) => {
const key = section path.join('|')
const existing = res[key] || {ids: [], section, path}
existing.ids = [...existing.ids, ...ids]
res[key] = existing
return res
}, {}))
console.log(compacted)
uj5u.com熱心網友回復:
以下是實作目標的一種可能方式。
代碼片段
// method to compact array of objects
const compactArr = arr => (
Object.values( // extract values from intermediate result-obj
arr.reduce( // iterate over the array using "reduce"
(acc, itm) => { // "acc" is the accumuator/aggregator
const {section, ids, path} = itm; // de-structure to get props
// construct uniq-key using "section" and "path"
const uniqKey = `${section}-${path.join('-')}`;
acc[uniqKey] = {
...(acc[uniqKey] || {}),
section, path, // if "section" already exists, concat "ids"
ids: (acc[uniqKey]?.ids ?? []).concat(ids)
}
return acc;
},
{} // initial value of "acc" is empty-object {}
)
) // implicit return from method
);
const arrayToBeCompacted = [{
section: "Section name 1",
path: ["segment1", "segment2"],
ids: ["id1"]
},
{
section: "Section name 1",
path: ["segment1", "segment2"],
ids: ["id2"]
},
{
section: "Section name2",
path: ["segment1", "segment2"],
ids: ["id3"]
},
{
section: "Another section",
path: ["segment1", "segment2"],
ids: ["id4"]
},
{
section: "Another section",
path: ["segment1", "segment2"],
ids: ["id5"]
},
];
console.log('compacted array: ', compactArr(arrayToBeCompacted));
.as-console-wrapper { max-height: 100% !important; top: 0 }
解釋
在上面的代碼段中添加了行內注釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/461456.html
標籤:javascript 罗达什
