Skip to content
Advertisement

Get a value from a multidimensional array

I have a multidimensional array as follows:

var schMatrix = [
    ['Weight',100,200,300,400,500,600,700,800,900,1000,1100,1200,1300,1400,1500,1600,1700,1800,1900,2000],
    ['Rate',395,413,484,560,635,691,763,837,910,982,1082,1155,1231,1304,1379,1452,1527,1570,1676,1750],
    ];

In my form the user would input a weight. What I am trying to do is if the weight is equal to or below the number in the weight part of the array that the corresponding rate is assigned to a variable.

Am stuck on how to do this. Any push in the right direction is appreciated.

Advertisement

Answer

First of all i would suggest you use a Object instead of a 2d-Array:

let schMatrix = {
    "Weight": [...,...,...],
    "Rate": [...,...,...]
}

Then you can itterate through the “Weight”-Array:

for (let i = 0; i < schMatrix["Weight"].length; i++) {
    if(schMatrix["Weight"][i] >= inputWeight){
        rate = schMatrix["Rate"][i]
    }
}
Advertisement