14

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 = [];
var k = 0;
for (var i = 0; i < 10; i++) {
  array[i] = [];
  for (var j = 0; j < 100; j++) {
    k = k + 1
    array[i].push(k);
  }
}
var index = array.indexOf(`**"What to insert here???"**`);
7
  • You have to iterate elements to find nested value. Commented Apr 19, 2013 at 10:14
  • 4
    What's k? Right now, the code above causes an error, because you try to read the value of k, but k isn't declared anywhere. Commented Apr 19, 2013 at 10:14
  • 1
    t-j-crowder: k is a global variable which is set to 0. Commented Apr 19, 2013 at 10:40
  • stackoverflow.com/about Commented May 11, 2013 at 9:48
  • 1
    @SherylHohman - I asked this on Apr 19, 2013, I wonder what triggered this comment. Commented Apr 20, 2022 at 5:01

8 Answers 8

27

JSFiddle

/**
 * Index of Multidimensional Array
 * @param arr {!Array} - the input array
 * @param k {object} - the value to search
 * @return {Array} 
 */
function getIndexOfK(arr, k) {
  for (var i = 0; i < arr.length; i++) {
    var index = arr[i].indexOf(k);
    if (index > -1) {
      return [i, index];
    }
  }
}

// Generate Sample Data
var k = 0;
var array = [];
for (var i = 0; i < 10; i++) {
  array[i] = [];
  for (var j = 0; j < 100; j++) {
    k = k + 1;
    array[i].push(k);
  }
}
var needle = 130;
var result = getIndexOfK(array, needle);
console.log('The value #' + needle + ' is located at array[' + result[0] + '][' + result[1] + '].');

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

There is WIP for Array.findIndex
2

With findIndex() and indexOf() you can do it in 2 lines:

const valueToSearch = "whatever";
let row = yourArray.findIndex((elem)=>elem.includes(valueToSearch));
let column = yourArray[row].indexOf(valueToSearch);

1 Comment

Good, simple modern answer. I’m wrapped that into an array method in my answer below.
1

On jsfiddle

function indexOf2d(arr, val) {
    var index = [-1, -1];

    if (!Array.isArray(arr)) {
        return index;
    }

    arr.some(function (sub, posX) {
        if (!Array.isArray(sub)) {
            return false;
        }

        var posY = sub.indexOf(val);

        if (posY !== -1) {
            index[0] = posX;
            index[1] = posY;
            return true;
        }

        return false;
    });

    return index;
}

console.log(indexOf2d(array, 50));

Comments

0

My code does like a PROCV in MS Excel... and identifies the Index searching only in the first column. Maybe help you (or others).

var convertToRoman = function (valueLimitTen) {   
  var convertTable = [  [1, "I"],
                        [2, "II"],
                        [3, "III"],
                        [4, "IV"],
                        [5, "V"],
                        [6, "VI"],
                        [7, "VII"],
                        [8, "VIII"],
                        [9, "IV"],
                        [10, "X"],
                      ];

  var myIndex;  
  for(var i in convertTable){
    if(convertTable[i][0] == valueLimitTen){
      myIndex = i;      
      return convertTable[i][1];      
    }  
  }  
}

console.log(convertToRoman(2)); //Result II
console.log(convertToRoman(10)); //Result X

Comments

0

ES6 has made this considerably easier.

function findIndexOfNestedArray(nestedArray, searchArray) {
  return searchArray.findIndex(item => {
    return item.length === nestedArray.length
    && item.every((a, i) => a === nestedArray[i])
  })
}

Comments

0

There's a very simple way:

[1,2] === [1,2] // > false
JSON.stringify([1,2]) === JSON.stringify([1,2]) // > true

So we could do something like:

arrays.findIndex(array => JSON.stringify(array)  === JSON.stringify(arrayToCompare))

Comments

0

@Pablito Praderio has a good modern solution above. I have wrapped that into an array method for convenience.

Here is a code snippet:

//  An array of characters:
    array = [];
    for(let i=0; i<5; i++) {
        array[i] = [];
        for(let j=0; j<5; j++) {
            array[i][j] = String.fromCharCode(65+i*5+j);
        }
    }

//  Now add the following method:

    array.coords = function(value) {
        let r = this.findIndex(r => r.includes(value));
        let c = this[r].indexOf(value);
        return [r,c];
    };
  
//  Get Index of, say 'Q'

    console.log(array.coords('Q'));
  

I’ve resisted the urge to add this to the Array prototype, but it makes sense to add it to the individual array object. In any case, you probably only want it for a particular array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.