Let's write a makeOrderList function that takes an order string and returns an object whose keys are the product names and whose values are the quantity.
in the order, the quantity always comes before the name of the product products are separated by a comma and one space if the product name consists of several words, write them in snake_case for an empty string, return an empty object
function makeOrderList(order) {}
Example:
const order = '1 coca cola, 5 chicken nuggets, 20 egg';
const list = makeOrderList(order);
/*
list === {
coca_cola: 1,
chicken_nuggets: 5,
egg: 20,
}
*/
I tried to split it and join, but i recieved something strange
CodePudding user response:
You can use a regular expression like digits then spaces then anything but comma
and .replace
it with a callback function that populates the object:
const order = '1 coca cola, 5 chicken nuggets, 20 egg';
const result = {}
order.replace(/(\d )\s ([^,] )/g, (_, qty, name) => result[name] = Number(qty))
console.log(result)
CodePudding user response:
This can also be solved using string methods.
const order = '1 coca cola, 5 chicken nuggets, 20 egg';
const makeOrderList = (arg)=> arg.split(', ').reduce((acc, str)=>{
const strArr = str.split(' ')
const val = strArr.shift()
acc[strArr.join('_')] = val
return acc
},{})
console.log(makeOrderList(order))