Вы можете использовать _.groupBy()
с _.head()
, чтобы сгруппировать все записи с одним и тем же первым элементом. Затем сопоставьте группы и суммируйте (с _.sumBy()
и _.last()
) 2-е элементы каждой группы:
const currArray = [["a",2],["b",3],["c",5],["a",2],["b",4],["d",6]]
const result = _.map(
_.groupBy(currArray, _.head), // group by the 1st item
(group, key) => [key, _.sumBy(group, _.last)] // take the key from each group, and sum all the 2nd items of each group
)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
С помощью lodash / fp вы можете создать функцию с _.flow()
, которая группирует элементы по 1-му элементу, суммирует 2-й элемент каждой группы и конвертирует к записям:
const { flow, groupBy, head, mapValues, sumBy, last, toPairs } = _
const fn = flow(
groupBy(head), // group by the 1st item
mapValues(sumBy(last)), // take the key from each group, and sum all the 2nd items of each group
toPairs // convert to entries
)
const currArray = [["a",2],["b",3],["c",5],["a",2],["b",4],["d",6]]
const result = fn(currArray)
console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>