Reputation: 13
I'm a newbie JS developer that has been struggling with a particular problem for a while, it's kind of hard to explain(as seen from the title) so I'll show the problem together with my answers if that will help.
First create an array of objects called data with the following values:
Principal- 2000, time- 3
Write a function called "interestCalculator" that takes an array as a single argument and does the following:
The function should return an array of objects called 'interestData' and each individual object should have 'principal', 'rate', 'time' and 'interest' as keys with their corresponding values. Log the 'interestData' array to console BEFORE your return statement. Finally, call/execute the function and pass the 'data' array you created.
ANSWER:
const Data = [
{
Principal: 2500,
Time: 1.8
},
{
Principal: 1000,
Time: 5
},
{
Principal: 3000,
Time: 1
},
{
Principal: 2000,
Time: 3
}
];
let rate;
const interestCalculator = (array) =>{
const interestData = array.map(item =>{
const {Principal, Time} = item;
if(Principal>=2500 && Time >= 1 && time < 3){
rate = 3;
}
else if(Principal>=2500 && Time >= 3){
rate = 4;
}
else if(Principal<2500 || Time <= 1){
rate=2;
}
else{
rate = 1;
}
const interest = (Principal * rate * Time)/100;
item.interest = interest;
item.rate= rate;
});
console.log(interestData);
return interestCalculator();
}
The above code returns "undefined" in the console. So I tried another way:
const interestCalculator = (item) =>{
let rate;
if(Principal>=2500 && Time >= 1 && time < 3){
rate = 3;
}
else if(Principal>=2500 && Time >= 3){
rate = 4;
}
else if(Principal<2500 || Time <= 1){
rate = 2;
}
else{
rate = 1;
}
const interest = (Principal * rate * Time)/100;
const interestData = [item.Principal, item.rate, item.Time, item.interest];
console.log (interestData);
return interestCalculator();
}
Still undefined...I tried different methods(foreach(), arr.push()) that I currently know of but to no avail. Im pretty stumped and any help will greatly be appreciated. Sorry for the long post. Thank you.
Upvotes: 1
Views: 138
Reputation: 14413
You need to return item
from inside the .map()
and call the interestCalculator
with Data
as an argument like below:
const Data = [{
Principal: 2500,
Time: 1.8
},
{
Principal: 1000,
Time: 5
},
{
Principal: 3000,
Time: 1
},
{
Principal: 2000,
Time: 3
}
];
let rate;
const interestCalculator = (array) => {
const interestData = array.map(item => {
const {
Principal,
Time
} = item;
if (Principal >= 2500 && Time >= 1 && Time < 3) {
rate = 3;
} else if (Principal >= 2500 && Time >= 3) {
rate = 4;
} else if (Principal < 2500 || Time <= 1) {
rate = 2;
} else {
rate = 1;
}
const interest = (Principal * rate * Time) / 100;
item.interest = interest;
item.rate = rate;
return item;
});
return interestData;
}
console.log(interestCalculator(Data));
Upvotes: 0