1

I want to change the ing array using map method into newIng where I changed the units.

const unitsLong = ['tablespoons', 'tablespoon', 'ounces', 'ounce', 'teaspoons', 'teaspoon', 'cups', 'pounds'];
const unitsShort = ['tbsp', 'tbsp', 'oz', 'oz', 'tsp', 'tsp', 'cup', 'pound'];

let ing = [
"8 ounces cream cheese, softened",
"1/4 teaspoon garlic powder",
" teaspoon dried oregano",
" teaspoon dried parsley",
" teaspoon dried basil",
"1 cups shredded mozzarella cheese",
"1 cups parmesan cheese",
"1 cups pizza sauce",
"1/4 cups chopped green bell pepper",
"1/4 cups chopped onion",
"2 ounces sliced pepperoni"
];

const newIng = ing.map(el => {
  unitsLong.forEach((unit, i) => {
    el = el.replace(unit, unitsShort[i]);
    });

});

console.log(newIng);

My expected result would be the same array where the units are shortened. Thanks!

4
  • 3
    Your .map callback isn't returning anything Commented Sep 27, 2019 at 9:53
  • what goes wrong? Commented Sep 27, 2019 at 9:54
  • @CertainPerformance, I tried returning ing or newIng. but I still don't get my output. Commented Sep 27, 2019 at 10:09
  • in map return el; Commented Sep 27, 2019 at 10:39

1 Answer 1

1

Beside the missing return statememt, you could reduce the array and take the changed string as accumulator.

var unitsLong = ['tablespoons', 'tablespoon', 'ounces', 'ounce', 'teaspoons', 'teaspoon', 'cups', 'pounds'],
    unitsShort = ['tbsp', 'tbsp', 'oz', 'oz', 'tsp', 'tsp', 'cup', 'pound'],
    ing = ["8 ounces cream cheese, softened", "1/4 teaspoon garlic powder", " teaspoon dried oregano", " teaspoon dried parsley", " teaspoon dried basil", "1 cups shredded mozzarella cheese", "1 cups parmesan cheese", "1 cups pizza sauce", "1/4 cups chopped green bell pepper", "1/4 cups chopped onion", "2 ounces sliced pepperoni"],
    newIng = ing.map(el => unitsLong.reduce((s, unit, i) => s.replace(unit, unitsShort[i]), el));

console.log(newIng);

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

Comments

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.