Home > Software design >  Accessing nested array properties in external array
Accessing nested array properties in external array

Time:06-08

Another beginner question which I would be extremely appreciative of an answer and explanation to.

I have an external database:

var DB = [["euro", 1.2], ["gbp", 1.5], ["yen", 1.3]];

and a function:

function Converter (arg, arr, curr) {

if (arg === "convert" ) {}
return (arr[1] * euro rate from db) / gbp rate from db;

and here is an example of a expected ouput:

Converter("convert", ["euro", 100], "gbp");
80; // expected output

Now, I know that I need to take arr[1] (amount of money to convert), multiply by the euro's exchange rate (in DB) and divide that by the GBP exchange rate (also in DB) to get the answer of 80. However I have tried every which way and can't seem to find the code to extract the information from the DB to write the sum (arr[1] * euro rate / gbp rate) to return my result.

Any pointers in the right direction would be very helpful.

CodePudding user response:

It seems you are stuck on finding a rate for a particular currency from your DB array. Check the "getRateForCurrency" function below.

var DB = [["euro", 1.2], ["gbp", 1.5], ["yen", 1.3]];

const getRateForCurrency = (curr) => {
  return DB.find(el => el[0] === curr)[1];
};

function Converter (arg, arr, curr) {
  if (arg === "convert" ) {
    return arr[1] * getRateForCurrency(arr[0]) / getRateForCurrency("gbp");
  }
}

const output = Converter("convert", ["euro", 100], "gbp");

console.log(output);

CodePudding user response:

Providing that the DB structure is unchangeable, you can use the following code to fetch the values.

const euroValue = (DB.find(element => element[0] === "euro"))[1];
const gbpValue = (DB.find(element => element[0] === "gap"))[1];

The above code is very costly since you need to iterate through all the values in the array for every query. the time complexity for the above method is O(n)

You can do the same query in O(1) time complexity if you use objects for storing the DB values, example provided below

const DB = {euro: 1.2, gbp: 1.5, yen: 1.3};
  • Related