Bijan
Bijan

Reputation: 8586

Javascript search for element in multidimensional array

I have the following code to combine an array and an array of arrays.

var arr1 = ["A", "B", "C", "D"];
var arr2 = [[1, 2, 3, 4, 3, 2],
            [4, 3, 7, 2, 5, 3],
            [8, 1, 9, 2, 8, 4],
            [2, 5, 9, 8, 7, 6],
           ]
var result = [], i = -1;

while ( arr1[++i] ) { 
  result.push( [ arr1[i], arr2[i] ] );
}

Here is how the final array looks

var final =[["A", [1, 2, 3, 4, 3, 2]],
            ["B", [4, 3, 7, 2, 5, 3]],
            ["C", [8, 1, 9, 2, 8, 4]],
            ["D", [2, 5, 9, 8, 7, 6]],
           ]

I am trying to create a function where I supply the letter and the index of the column # i want to return from the array of arrays.

i.e. If I give it B and 2, it would return result[1][1][2] which is 7.

If I give it D and 5, it would return result[3][1][5] which is 6

I tried using indexOf but it is hard to search for since this array has 3 dimensions.

Here is a jsFiddle I made of my sample Any help would be appreciated

Edit: It seems my only problem is returning the column # where the letter occurs. How would I use indexOf to search for the occurence of a letter in first column?

Upvotes: 1

Views: 3391

Answers (2)

leo.fcx
leo.fcx

Reputation: 6467

I'd suggest to change a little bit your logic as follows:

var result = {}; // Make this to be an object

while ( arr1[++i] ) { 
  result[ arr1[i] ] = arr2[i];
}

This will create an object similar to the following:

result = {
    "A": [1,2,3,4,3,2],
    "B": [4,3,7,2,5,3],
    "C": [8,1,9,2,8,4],
    "D": [2,5,9,8,7,6]
}

And the way to access data from it would be:

result['D'][5] // returns 6

See working DEMO here

Upvotes: 3

John Bupit
John Bupit

Reputation: 10618

How about this function:

function find(text, col) {
    for(var i = 0; i < result.length; i++)
        if(result[i][0].equals(text)) return result[i][1][col - 1];
    return null;
}

console.log(find("B", 3));

var arr1 = ["A", "B", "C", "D"];
var arr2 = [
  [1, 2, 3, 4, 3, 2],
  [4, 3, 7, 2, 5, 3],
  [8, 1, 9, 2, 8, 4],
  [2, 5, 9, 8, 7, 6],
]
var result = [],
  i = -1;

while (arr1[++i]) {
  result.push([arr1[i], arr2[i]]);
}

console.log(result)

//Try to find element where text == "B" and return the 3rd column
console.log(find("B", 3))

function find(text, col) {
  for (var i = 0; i < result.length; i++)
    if (result[i][0] == text) return result[i][1][col - 1];
  return null;
}

Upvotes: 1

Related Questions