I am having issues getting my function to return product of two variables with numerical values.
The directions are: You want to write a function that takes in the name of a stock as a string and returns for you the total amount of money you have invested in that stock. e.g. if your function is given ‘AMZN’ it should return 4000.
This is my function, I keep returning NaN when I should be returning 4000.
let investments = [
{stock: "AMZN", price: 400, numOfShares: 10},
{stock: "AAPL", price: 300, numOfShares: 5},
{stock: "BIDU", price: 250, numOfShares: 4}
];
calculateInvestedAmt = (stock) => {
const totalAmt = investments.price * investments.numOfShares;
return totalAmt;
};
calculateInvestedAmt("AMZN");
CodePudding user response:
You have to use find
method
const getStockPrice = (name) => {
const stock = investments.find(s => s.stock === name);
if (!stock) return undefined; // can't find stock
returb stock.price * stock.numOfShares;
}
CodePudding user response:
investments.price
and investments.numOfShares
is undefined. That's why it is producing NaN, because you are multiplying two undefined values. You should first iterate over investments
to find the stock you want.
CodePudding user response:
let investments = [
{stock: "AMZN", price: 400, numOfShares: 10},
{stock: "AMZN", price: 400, numOfShares: 10},
{stock: "AAPL", price: 300, numOfShares: 5},
{stock: "BIDU", price: 250, numOfShares: 4}
];
calculateInvestedAmt = (stockName) => {
var totalAmt;
var investedItem = investments.filter(invst => invst.stock === stockName);
investedItem.map(item => {
totalAmt = item.price * item.numOfShares;
});
return totalAmt;
};
console.log(calculateInvestedAmt("AMZN"));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>