在Javascript中查找多维数组的索引

时间:2013-04-19 10:12:33

标签: javascript

我在JavaScript中创建了一个多维数组,我想找到具体值的确切索引。该值将是用户输入。

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 index=array.indexOf(**"What to insert here???"**);

6 个答案:

答案 0 :(得分:15)

JSFiddle

&#13;
&#13;
/**
 * 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] + '].');
&#13;
&#13;
&#13;

答案 1 :(得分:2)

这个例子似乎也适用于IRREGULAR多维数组:

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);

我写得很快,所以每个人都被邀请改进这个功能!

P.S。现在该函数返回一个STRING值,所有索引用逗号分隔,您可以简单地编辑它以返回一个对象

答案 2 :(得分:1)

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));

答案 3 :(得分:0)

我的代码就像MS Excel中的PROCV ...,并且仅在第一列中标识索引搜索。也许可以帮助您(或其他人)。

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

答案 4 :(得分:0)

ES6 让这件事变得相当容易。

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

答案 5 :(得分:0)

复制并粘贴此代码

替换 <ma​​sterArray> 与您的主阵列(嵌套所有其他阵列)

代码:

//Remove Duplicates
  let stringArray = masterArray.map(item=>item.join('')); // transform all nested arrays into strings (for comparation)
  let nonDuplicated = [] // temporary array to compare data
  stringArray.forEach(nestedArrayString=>{
    let reapeatedIndex = nonDuplicated.indexOf(nestedArrayString); // this is the comparator
    if(reapeatedIndex>0){
      indexToRemove = stringArray.indexOf(nestedArrayString);
      console.log('---indexToRemove',indexToRemove)
      stringArray.splice(indexToRemove,1);
      masterArray.splice(indexToRemove,1);
    }else{nonDuplicated.push(nestedArrayString)}
  });
  //
  let lastString = stringArray.filter(foundString=>foundString===stringArray[stringArray.length-1])
  if(lastString.length>1){
    stringArray.splice(stringArray.length-1,1)
    masterArray.splice(masterArray.length-1,1)
  };
    console.log('>> masterArray',masterArray)

我一直在寻找删除数组内的数组的解决方案,并提供了这个丑陋但高效的解决方案: 处理数组数组(两次),但不能进一步嵌套。

这段代码会把嵌套的数组转成字符串 => 一一记录成一个临时数组 => 每次记录比较当前记录的字符串是否已经在数组中 .then 如果重复,则从 中删除masterArray(你的)和 stringArray 元素