Reputation: 43
Write a function called productOfValues which takes in an object of key/value pairs and multiplies the values together. You can assume that all keys are strings and all values are integers.
For example:
let testObject = {
'a': 5,
'b': 12,
'c': 3
}
productOfValues(testObject)
So, this is what I wrote:
let testObject = {
'a': 5,
'b': 12,
'c': 3,
'd': 1
}
let testObject_v = {
'z': 2,
'y': 2,
'x': 2,
'w': 2
}
function productOfValues(someObject) {
return someObject.a * someObject.b * someObject.c;
}
function productOfValues(testObject) {
return testObject_v.z * testObject_v.y * testObject_v.x * testObject_v.w;
}
console.log(productOfValues(testObject))
console.log(productOfValues(testObject_v))
And I've got an error of:
Your productOfValues function should return the product of the values in the given object: 180
Upvotes: 1
Views: 1491
Reputation: 3434
You're defining the same function twice and you're only multiplying the first 3 numbers in the first object. Instead, rewrite your productOfValues()
function to be something like this:
let testObject = {
'a': 5,
'b': 12,
'c': 3,
'd': 1
}
let testObject_v = {
'z': 2,
'y': 2,
'x': 2,
'w': 2
}
function productOfValues(someObject) {
let product = 1;
for (const i in someObject) {
product = product * someObject[i];
}
return product;
}
console.log(productOfValues(testObject))
console.log(productOfValues(testObject_v))
Edit:
Alternative productOfValues()
function:
function productOfValues(someObject) {
var result = 1;
var len = Object.keys(someObject).length;
for (var i = 0; i < len; i++) {
result = result * someObject[Object.keys(someObject)[i]];
}
return result;
}
Upvotes: 1
Reputation: 635
You can use Object.values
to convert your object to array of its values & then use reduce
to get the product of that values array
let testObject = {'a': 5,'b': 12,'c': 3, 'd':1};
let testObject_v = { 'z':2,'y':2,'x':2,'w':2 }
function productOfValues(someObject) {
return Object.values(someObject).reduce((a,b)=> a*b ,1);
}
console.log(productOfValues(testObject));
console.log(productOfValues(testObject_v));
Upvotes: 4