Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I sum numbers which are substrings in variables?

I was wondering how can you combine two variables (or more) that have the same string values, but different numbers.

For example, if you’re combining a list of ingredients that are present in two different recipes. For a shopping list, like:

let ingredient1 = 1 + " apple";
let ingredient2 = 2 + " apple";
//combining ingredient1 and ingredient 2 would produce something like totalIngredients = 3 apples;

I can kind of figure out the pluralization, but I can’t figure out how I can combine those two strings and for it to only increase the number if they’re matching.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Like others have noted, you should store your ingredients as objects. One way to achieve this is to have a class which stores the count and ingredient type. You can then define a function that checks for a given type and returns the count of ingredients.

class Ingredient {  
  constructor(count, type) {
    this.count = count;
    this.type = type;
  }
};

const countByType = (type) => ingredients.reduce((sum, ingredient) => {
  if (ingredient.type === type) {
    return sum += ingredient.count;
  }

  return sum;
}, 0);

const ingredients = [];
ingredients.push(new Ingredient(1, "apple"));
ingredients.push(new Ingredient(2, "apple"));
ingredients.push(new Ingredient(5, "orange"));



console.log(`${countByType("apple")} apples`);
console.log(`${countByType("orange")} oranges`);

If you prefer, you can achieve the same without classes as well:

const countByType = (type) => ingredients.reduce((sum, ingredient) => {
  if (ingredient.type === type) {
    return sum += ingredient.count;
  }

  return sum;
}, 0);

const ingredients = [];
ingredients.push({count: 1, type: "apple"});
ingredients.push({count: 2, type: "apple"});
ingredients.push({count: 5, type: "orange"});



console.log(`${countByType("apple")} apples`);
console.log(`${countByType("orange")} oranges`);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading