2 回答

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
我會(huì)做這樣的事情:
function groupProducts( input ) {
var productsById = input.reduce( function( current, item ) {
if( !current[ item.id ] ) {
current[ item.id ] = [];
}
current[ item.id ].push( item );
return current;
}, {} );
return Object.keys( productsById ).map( function( id ) {
productsById[ id ].reduce( function( current, item ) {
if( current ) {
// this could be extracted as a closure passed in to coalesce items together. Your rules for how that happens go here.
current.quantity += item.quantity;
current.price += item.price;
return current;
} else {
return Object.assign( {}, item ); // shallow copy beware
}
}, null );
} );
}
PS 我注意到在您的輸入示例中,數(shù)量和價(jià)格等內(nèi)容是字符串而不是數(shù)字。我將假設(shè)您知道如何理順這些事情,以便數(shù)據(jù)具有正確的數(shù)據(jù)類型。如果您有這些字符串,這將不起作用。

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是執(zhí)行此操作的一種簡(jiǎn)短方法(基于我之前引用的假設(shè),這quantity是每個(gè)具有相同id值的項(xiàng)目唯一可以變化的):
inputArray.reduce((result, item) => {
if (result.map.has(item.id)) {
result.map.get(item.id).quantity += item.quantity;
} else {
result.array.push(item);
result.map.set(item.id, item);
}
return result;
}, {map: new Map(), array: []}).array
reduce如果您不熟悉它,這將使用數(shù)組函數(shù)。這可以在沒有 的情況下完成Map,但這比搜索整個(gè)結(jié)果數(shù)組以查找id已經(jīng)看到的值更有效。
此代碼背后的想法是,您保留您看到的第一個(gè)項(xiàng)目,該項(xiàng)目具有id您以前從未見過的項(xiàng)目,如果您以前看過一個(gè)id項(xiàng)目,則查找該原始項(xiàng)目,并將新數(shù)量添加到之前的數(shù)量上。
添加回答
舉報(bào)