Mark
Mark

Reputation: 5653

javascript - loop multidimesntional array

I am sure this is really simple, I used to have a function for checking the contents of an array. Now Id like to modify it to check a two dimensional array.

function ChkArray(Str, Val){

for (var i=0;i<Str.length;i++){
        if (Str[i] == Val) {return i;}
    }
return -1;
}

My new attempt:

function ChkArray2(Str, Val){

for (var i=0;i<Str.length;i++){
        for (var ii=0;ii<Str[ii].length;ii++){
            if (Str[i][ii] == Val) {return i;}
        }
    }
return -1;
}

Upvotes: 0

Views: 199

Answers (3)

nickf
nickf

Reputation: 546035

If you're asking about better ways to tackle the problem, I would perhaps think about writing a function which can work with any number of dimensions in the array. In your example, the return value is the index of the top level array, but to make it generic, you would have to return the full "path" to the found element, and let the calling code decide what information it wants:

    function multiFind(arr, val) {  // please don't name an array "str"!
    for (var i = 0, l = arr.length; i < l; ++i) {
        if (arr[i] === val) {
            return [i];
        } else if (is_array(arr[i])) {
            var ret = multiFind(arr[i], val);
            if (ret !== false) {
                ret.unshift(i);
                return ret;
            }

        }
    }
    return false;
}

// this function by Doug Crockford
var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

var inp = ["a","b",["c", ["d", "e", ["f", "g"], "h"]]];

multiFind(inp, "a"); // [0]
multiFind(inp, "b"); // [1]
multiFind(inp, "c"); // [2, 0]
multiFind(inp, "f"); // [2, 1, 2, 0]
multiFind(inp, "h"); // [2, 1, 3]
multiFind(inp, "x"); // false

Upvotes: 1

Li0liQ
Li0liQ

Reputation: 11264

I suggest using javascript foreach.

function ChkArray2(Str, Val){    
    for (var i in Str){
        for (var ii in Str[i]){
            if (Str[i][ii] == Val){
                return i;
            }
        }
    }
    return -1;
}

Upvotes: -1

David Hedlund
David Hedlund

Reputation: 129792

Close, in your inner loop, you want to check the length of the current item in the outer loop:

function ChkArray2(Str, Val){

    for (var i=0;i<Str.length;i++){
        for (var ii=0;ii<Str[i].length;ii++){
            if (Str[i][ii] == Val) {return i;}
        }
    }
    return -1;
}

that should work

Upvotes: 2

Related Questions