Reputation: 399
I am making my first project as a food rota that gives out a shopping list from the chosen Recipe ingredients.
I managed to write the loop
that would combine all the ingredients in one array
where it takes us to my question.
I would like to combine the same ingredients in the array ie: [1kg Carrots, 1kg Spinach, 1kg Carrots]
, I would like it to combine the repeating (1kg Carrots, 1kg Carrots)
into (2kg Carrots)
Is there a way to do this?
Sorry if my request is sloppy, first time asking a question.
I could work it so that it would cancel out the similar ones as the outcome of [1kg Carrots, 1kg Carrots]
would be [1kg Carrot]
.
Unfortunately I am at work at the moment and do not have access - will update if needed.
Upvotes: 0
Views: 163
Reputation: 274
I would most likely create an object from the array.
const arr = ['1kg Carrots', '1kg Spinach', '1kg Carrots'];
let obj = {};
arr.forEach(element => {
let [kg, item] = element.split(' ');
kgNum = parseInt(kg);
if(Object.keys(obj).includes(item)){
return obj[item] += kgNum;
} else {
obj[item] = kgNum;
}
})
obj
// #=> { Carrots: 2, Spinach: 1 }
obj
already has a key of item
and if it doesn't I add itkgNum
This is a good place to start and you can figure out with a little more work of how to add back the kg
:)
Upvotes: 1
Reputation: 1901
it can be done in 2 steps
var arr = ["1kg Carrots", "1kg Spinach", "1kg Carrots"]
step 1: count total number of kg
var arrCount = arr.reduce((ac, val)=> {
var [kg, key] = val.split(' ')
kg = parseFloat(kg)
ac[key] = ac[key]? ac[key]+kg : kg;
return ac
}, {}) // { Carrots: 2, Spinach: 1 }
step 2: revert it to array
var out = Object.entries(arrCount).map(([key, kg])=> `${kg}kg ${key}`)
// [2kg Carrots, 1kg Carrots]
Upvotes: 1