0

I'm working on a calculation form that generates a multi-dimensional array with two values [selection], something like:

[[10,0.5], [18,0.75]]

The second array [lookup-table] contains a range of values:

["10","0.5","0.1"], ["12","0.5","1.1"], ["14","0.5","3.1"], ["16","0.5","5.1"],["18","0.5","7.1"], ["20","0.5","9.6"], ["22","0.5","11.6"]... ["18","0.75","9.1"]

I'm trying to match the index [0], [1] values in the [selection] array with the same index values in the [lookup-table] array.

["10","0.5","0.1"]... ["18","0.75","9.1"]

Once this is done, I'd like to retrieve the value for the index [x][2] value in the [lookup-table]:

["10","0.5","0.1"]... ["18","0.75", "9.1"]

I did find a very helpful and similar question here: JavaScript - Compare two multidimensional arrays

And in the console, it seems to correctly identify matches in the array index.

I'm using more or less a similar function:

function find(haystack, needles) {
   var lookupValue = [];
    //Iterate through all elements in first array

    for(var x = 0; x < haystack.length; x++){

        //Iterate through all elements in second array    
        for(var y = 0; y < needles.length; y++){

          /*This causes us to compare all elements 
             in first array to each element in second array
            Since haystack[x] stays fixed while needles[y] iterates through second array.
             We compare the first two indexes of each array in conditional
          */

          if(haystack[x][0] == needles[y][0] && haystack[x][1] == needles[y][1]){
            console.log("match found");
            console.log("Array 1 element with index " + x + " matches Array 2 element with index " + y);

            //Retrieve the price for the high and low lookup values and store in array
            lookupValue = haystack[x][2];

          }
      }
    }
    return lookupValue;
  }

  var totalResult = find(lookupTable, flushGrowthArray ).toString();

However when I try to retrieve the haystack[x][2] indexed value from the matches in the [lookup-table], for some reason I'm only returning a single value.

I think that it's probably a very simple mistake; what am I doing wrong? I appreciate any new insights.

Community
  • 1
  • 1
tnog
  • 420
  • 3
  • 12
  • You're replacing `lookupValue` with each found match, you're not pushing the match onto the array. – Barmar Apr 10 '15 at 23:54
  • Ah, that makes sense. And the reason why I'm only retrieving the last value retrieved. – tnog Apr 10 '15 at 23:55

1 Answers1

1
lookupValue = haystack[x][2];

should be:

lookupValue.push(haystack[x][2]);

so you add the match to the array.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks, that definitely led me in the right direction. I'm still getting a grasp of working with arrays in Javascript. – tnog Apr 11 '15 at 00:00