Looping Through Multidimensional Array with Nested Arrays

Hi all,

myArray = [
[["ALBL","BLAL"],["TDBL"],["TDAL"],"ABL"],
[["CLDL","DLCL"],["TDDL"],"CDL"],
[["ELFL","FLEL"],["TDFL"],"EFL"],

]

I am trying to check if a value exists in the first nested array of myArray.
For example the value DLCL

I’ve tried the following but can’t get it to work properly

var found = ""
for(var i = 0; i < myArray.length; i++) { 
	for(var j = 0; j < myArray[i].length; j++) { // 
		for(var k = 0; k < myArray[j].length; k++) {
			if (myArray[i][j][k] === "DLCL") {
				found = true;
				break;
			}
		}
	}
}

Any ideas of what is going wrong here?

What error are you getting in the console?

Hello mawburn,

I am not at my computer now but the error was on the following line

for(var k = 0; k < myArray[j].length; k++)

By the way, is the way I am trying to accomplish it a good way?

This line has an error:

for(var k = 0; k < myArray[j].length; k++) {

Here you’re trying to loop through an array that you’re already looping (myArray[i])

You should go one level deeper:

for(var k = 0; k < myArray[i][j].length; k++) {

I would use recursion for that. Here is my implementation:

Array.prototype.find = function(query){
 	
    for (var index in this){
    	var value = this[index];
        if (typeof(value.find) === 'function'){
            if(value.find(query)) { return true; }
        }
        if (value == query){
            return true;
        }
    }
    
    return false;
    
}

Usage:

var found = myArray.find('DLCL');

Live demo: http://jsfiddle.net/6r2t81w8/

That function doesn’t have hardcoded number of levels. It will find the value on any nested level.

That worked megazoid.
As for your solution, I don’t understand a thing of it :frowning:
This will take some time to understand.
Thank you for sharing your knowledge!

I’ve added comments here: http://jsfiddle.net/6r2t81w8/1/
Hope they will help to get the idea

I have to give it a try.
Thanks for the details, that helps a lot!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.