0

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.

2

2 Answers 2

1

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 }
  1. I loop over the array
  2. I split the element (eg. '1kg Carrots') into the weight and item
  3. then I coerce the 1kg into an integer
  4. I check if the obj already has a key of item and if it doesn't I add it
  5. If it does already exist I just increment kgNum
  6. and then I return the object

This is a good place to start and you can figure out with a little more work of how to add back the kg :)

Sign up to request clarification or add additional context in comments.

Comments

1

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] 

1 Comment

Thanks, I will try this out as soon as I get home and will let you know the results It looks like this would definitely solve my problem though ( I dont necessarily need the kg part I can assume that anyway :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.