Search code examples
javascriptarrayssortingobjectjavascript-objects

JavaScript get first two words from string in Array


I am new to JavaScript so I am struggling to even know where to start. Please can someone help me. I have this array of ingredients:

const ingris =  [
  "1 cup heavy cream",
  "8 ounces paprika",
  "1 Chopped Tomato",
  "1/2 Cup yogurt",
  "1 packet pasta ",
  "1/2 teaspoon freshly ground black pepper, divided",
]

I am trying to take out for example the 1 cup or 1/2 teaspoon (first 2 words of the array) and add it to a new array of objects like below:

const ShoppingList = [
  {
    val: "heavy cream",
    amount: "1 cup",
  },
  {
    val: "Tomato",
    amount: "1 Chopped ",
  },
  {
    val: "yogurt",
    amount: "1/2 Cup",
  },
];

Solution

  • Probably I would try to use .map() first iterate through the array of strings and convert it into an new array of objects. On each iteration you can .split() the string by spaces and most probably the first 2 elements of the array can be the amount property and the rest is the value.

    See from the documentations:

    The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

    The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.

    Try as the following:

    const ingris = [
      "1 cup heavy cream",
      "8 ounces paprika",
      "1 Chopped Tomato",
      "1/2 Cup yogurt",
      "1 packet pasta",
      "1/2 teaspoon freshly ground black pepper, divided",
    ];
    
    const result = ingris.map(e => {
      const split = e.split(' ');
      const amount = `${split[0]} ${split[1]}`;
      
      return { val: e.replace(`${amount} `, ''), amount };
    });
    
    console.log(result);

    Probably you need to add fallback once you have different format of input strings, like checking if you have at least 3 words in that string.