function storage(data) {
let object = {};
data.forEach(line => {
let [product, quantity] = line.split(' ');
if (!object[product]) {
object[product] = quantity;
} else {
let currentQuantity = Object.assign(object[product] = quantity); < -- - problem comes from here
let newQuantity = Number(currentQuantity) Number(quantity);
Object.assign(product, newQuantity);
}
});
}
storage(['tomatoes 10', 'coffee 5', 'olives 100', 'coffee 40']);
Hello , I am new in the OOP and I want to combine different values from a key with same name.
output wanted ['tomatoes 10', 'coffee 45', 'olives 100']
CodePudding user response:
You shouldn't be using Object.assign()
. That's for merging objects, not assigning a specific property. Just retrieve and assign object[product]
.
At the end you need to convert object
back to an array of strings and return that.
function storage(data) {
let object = {};
data.forEach(line => {
let [product, quantity] = line.split(' ');
quantity = Number(quantity);
if (!object[product]) {
object[product] = quantity;
} else {
object[product] = quantity;
}
});
return Object.entries(object).map(([key, value]) => `${key} ${value}`);
}
console.log(storage(['tomatoes 10', 'coffee 5', 'olives 100', 'coffee 40']));
CodePudding user response:
You can simplify this a lot. There's no real benefit to be gained from using Object.assign
. You probably also want to explicitly convert your quantities to numbers instead of using strings.
let displayStock = (data) => Object.entries(data).map( ([k, v]) => `${k} ${v}` )
function storage(data) {
let object = {};
data.forEach(line => {
let [product, quantity] = line.split(' ');
object[product] = (object[product] || 0) Number(quantity)
});
return object;
}
let stock = storage(['tomatoes 10', 'coffee 5', 'olives 100', 'coffee 40']);
console.log(displayStock(stock))