Raquel Santos
Raquel Santos

Reputation: 110

How to return a value from a function , use that value to make a math formula and push the solution(key/value) to an array of objects?

This is the exercise problem I need to solve:

"1- First create an array of objects called data with the following values:

  1. Principal- 2500, time- 1.8

  2. Principal- 1000, time- 5

  3. Principal- 3000, time- 1

  4. Principal- 2000, time- 3

  NB: Each individual object should have 'principal' and 'time' as keys.

2- Write a function called "interestCalculator" that takes an array as a single argument and does the following

  Determine the rate applicable using the conditions:

  If the principal is greater than or equal to 2500 and the time is greater than 1 and less than 3, then rate = 3

  If the principal is greater than or equal to 2500 and the time is greater than or equal to 3, then rate = 4

  If the principal is less than 2500 or the time is less than or equal to 1, then rate = 2

  Otherwise, rate = 1;

3- Calculate the interest for each individual object using the formula: (principal * rate * time) / 100.

4- 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.

5- Log the 'interestData' array to console BEFORE your return statement.

6- Finally, call/execute the function and pass the 'data' array you created."

What I did so far: I did the array with objects with two properties (principal and time) with their values. Then I created the function that will make a loop in every object and calculate the rate (that is not yet included in the object) then I want to return for each object the value of the rate and calculate the formula ((principal * rate * time) / 100) after that I want to make a new array including those new two properties (rate and interest data) and their values. Can anybody help me solve this challenge explaining with comments?

Here is my code:

const Data = [
  {
    principal: 2500, //3
    time: 1.8
  },
  {
    principal: 1000, //1
    time: 5
  },
  {
    principal: 3000, //1
    time: 1
  },
  {
    principal: 2000, //2
    time: 3
  }
];

const interestCalculator = Data => {
  // here I create a forEach loop
  Data.forEach(individualData => {
    // here I start the rate with empty string
    let rate = "";

    //use if...else statement to return the rate for each indivual Object
    if (individualData.principal >= 2500 && individualData.time > 1 && individualData.time < 3) {
      rate = 3;
    } else if (individualData.principal <= 2500 || individualData.time <= 1) {
      rate = 2;
    } else {
      rate = 1;
    }

    return rate;
  });

  // stoped here and I need help to solve the challenge
};

Upvotes: 2

Views: 368

Answers (3)

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6418

Here I try to write the program with proper documentation. You can read it. If you have any query then feel free to contact me.

const Data = [{principal: 2500,time: 1.8}, {principal: 1000,time: 5}, {principal: 3000,time: 1}, {principal: 2000,time: 3}];

const interestCalculator = (data) => {
    /**
     * Iterate through the data array using `Array.prototype.map()`
     * The map will visit every element of the array and after
     * performing it's job it returns a new array.
     *
     * Here we store our returning array into `interestData` array
     *
     */
    const interestData = data.map(item => {

        if (item.principal >= 2500 && (item.time > 1 && item.time < 3)) {
            /**
             * If the principal is greater than or equal to 2500
             * and the time is greater than 1 and less than 3,
             * then rate = 3
             */
            item.rate = 3;
        } else if (item.principal >= 2500 && item.time >= 3) {
            /**
             * If the principal is greater than or equal to 2500
             * and the time is greater than or equal to 3,
             * then rate = 4
             */
            item.rate = 4;
        } else if (item.principal < 2500 || item.time <= 1) {
            /**
             * If the principal is less than 2500
             * OR the time is less than or equal to 1,
             * then rate = 2
             */
            item.rate = 2;
        } else {
            item.rate = 1;
        }

        /**
         * Calculate the interest and insert it into the object
         * of array element
         *
         */
        item.interest = (item.principal * item.rate * item.time) / 100;

        return item;
    });

    /**
     * Console the calculated Data using `console.table()`
     * The console.table() will show you a beautiful tabular
     * form of your data.
     */
    // console.table(interestData);
    console.log(interestData); // For displaying into stackoverflow's snippet I use log instead of table.

    // Return the new array
    return interestData;
}

// Call the function for execution.
interestCalculator(Data);
.as-console-wrapper {min-height: 100% !important; top: 0;}

This is how console.table() shows at vscode's output terminal. enter image description here

And this is the chrome's console view enter image description here

Upvotes: 1

vrintle
vrintle

Reputation: 5596

You're almost done, nice approach till now.

Firstly, you'd said "I want to make a new array including those new two properties", then you should have a look at these super methods,

These methods are converse of each other. So, using these methods, you can deep-clone your array as follows:

let newData = JSON.parse(JSON.stringify(Data));

Note that, you can set new properties in JS objects like,

Object.property = value;

Now, you've to set the rate property, then do

// set the property rate
individualData.rate = rate; 

Similarly, you can set other properties also. Further, if you want to retrieve any property, then you can simply do

console.log(Object.property);

So, you can calculate the interest as follows

// calculate the interest with the formula
individualData.interest = individualData.principal * individualData.rate * individualData.time / 100;

We're almost done! Finally, to log the resultant array of objects, return the value

return newData;

const Data = [
  {
    principal: 2500, //3
    time: 1.8
  },
  {
    principal: 1000, //1
    time: 5
  },
  {
    principal: 3000, //1
    time: 1
  },
  {
    principal: 2000, //2
    time: 3
  }
];

const interestCalculator = Data => {
  // The following method is best to deep-clone an array!
  // Very important method for development purpose
  let newData = JSON.parse(JSON.stringify(Data));
  
  // here I create a forEach loop
  newData.forEach(individualData => {
    // here I start the rate with empty string
    // NO, rate is integer, so initiate it with a number, eg. 0
    let rate = 0;

    // use if...else statement to return the rate for each individual Object
    if (individualData.principal >= 2500 && individualData.time >= 3) {
      rate = 4;
    } else if (individualData.principal >= 2500 && individualData.time > 1 && individualData.time < 3) {
      rate = 3;
    } else if (individualData.principal < 2500 || individualData.time <= 1) {
      rate = 2;
    } else {
      rate = 1;
    }

    ///// I ADDED LINES HERE /////
    
    // set the property rate
    individualData.rate = rate; 
    
    // calculate the interest with the formula
    individualData.interest = individualData.principal * individualData.rate * individualData.time / 100; 
  });
  
  // return the Data array with rate and interest inserted to each objects
  return newData; // very important!
};

console.log('Original array', Data);

console.log('New array', interestCalculator(Data)); // log the returned value

EDIT: I think you'd forgot to add the second condition to calculate rate. I've added that in the above snippet. Also, in your code, you'd a small typo, regarding the last condition. It is, individualData.principal < 2500 (less than).

Upvotes: 4

Omri Attiya
Omri Attiya

Reputation: 4037

So I used map in order to modify the array and I created a function that calculates rate (just for good practice), and also added a missing case in rate (you don't have rate 4).

I think it looks much more readable and it's not hard to add keys to objects just practice that :D

const data = [{
    principal: 2500, //3
    time: 1.8
  },
  {
    principal: 1000, //1
    time: 5
  },
  {
    principal: 3000, //1
    time: 1
  },
  {
    principal: 2000, //2
    time: 3
  }
];

function interestCalculator(data) {
  // deep copy the original array
  let newData = JSON.parse(JSON.stringify(data))
  newData.map(item => {
    item.rate = getRate(item.principal, item.time);
    item.interest = (item.principal * item.rate * item.time) / 100;
    return item;
  });
  console.log(newData);
  return newData;
};

function getRate(principal, time) {
  if (principal >= 2500) {
    if (time > 1 && time < 3)
      return 3;
    else if (time == 3) return 4;
  } else if (principal <= 2500 || time <= 1) {
    return 2;
  }
  return 1;

}

interestCalculator(data);

Upvotes: 2

Related Questions