To find Index of Multidimensional Array in Javascript

后端 未结 4 2114
刺人心
刺人心 2020-11-27 22:22

I have created a multidimensional array in JavaScript and I want to find the exact index of specific value. That value will be user input.

var array=[];
for(         


        
4条回答
  •  天命终不由人
    2020-11-27 22:53

    this example seems to work well also with IRREGULAR multidimentional array:

    function findIndex(valueToSearch, theArray, currentIndex) {
        if (currentIndex == undefined) currentIndex = '';
            if(Array.isArray(theArray)) {
                for (var i = 0; i < theArray.length; i++) {
                    if(Array.isArray(theArray[i])) {
                        newIndex = findIndex(valueToSearch, theArray[i], currentIndex + i + ',');
                        if (newIndex) return newIndex;
                   } else if (theArray[i] == valueToSearch) {
                       return currentIndex + i;
                   }
                }
        } else if (theArray == valueToSearch) {
            return currentIndex + i;
        }
        return false;
    }
    
    var a = new Array();
    a[0] = new Array(1, 2, 3, 4, 5);
    a[1] = 'ciao';
    a[2] = new Array(new Array(6,7),new Array(8,9),10);
    
    var specificIndex = findIndex('10', a);
    

    i wrote this speedly so everyone is invited to improve this function!

    p.s. now the function returns a STRING value with all indexes separated by comma, you can simply edit it to returns an object

提交回复
热议问题