Me preguntaba cómo puedes combinar dos variables (o más) que tienen los mismos valores de cadena, pero números diferentes.
Por ejemplo, si está combinando una lista de ingredientes que están presentes en dos recetas diferentes. Para una lista de compras, como:
let ingredient1 = 1 + " apple"; let ingredient2 = 2 + " apple"; //combining ingredient1 and ingredient 2 would produce something like totalIngredients = 3 apples;Puedo descifrar la pluralización, pero no puedo descifrar cómo puedo combinar esas dos cadenas y que solo aumente el número si coinciden.
Como han señalado otros, debe almacenar sus ingredientes como objetos. Una forma de lograr esto es tener una clase que almacene el conteo y el tipo de ingrediente. Luego puede definir una función que verifique un tipo determinado y devuelva el recuento de ingredientes.
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`);Si lo prefiere, también puede lograr lo mismo sin clases:
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`);¿Cómo puedo sumar números que son subcadenas en variables?
Convirtiendo las subcadenas en números. Si los números están al comienzo de la cadena, puede usar parseInt .
parseInt(ingredient1) + parseInt(ingredient2)Para verificar los tipos, puede usar, por ejemplo
let ingredient1 = 1 + " apple"; let ingredient2 = 2 + " apple"; let type1 = ingredient1.slice(ingredient1.indexOf(' ') + 1); let type2 = ingredient2.slice(ingredient2.indexOf(' ') + 1); if (type1 === type2) { console.log(`${parseInt(ingredient1) + parseInt(ingredient2)} ${type1}`); }No puedes combinar ambos ingredientes y debería hacer un cálculo porque let ingredient1 = 1 + " apple"; produce una cadena 1 apple
Puedes hacer algo como esto:
let ingredient = 'apple' let ingredient1 = 1 let ingredient2 = 2 let totalIngredients = ingredient1 + ingredient2 + ingredient O tal vez use un ciclo for para recorrer todos los ingredientes y agregarlo al total y luego agregar 'apple'