11

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

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???"**`);
4

6 回答 6

25

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] + '].');

于 2013-04-19T10:27:19.647 回答
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);

我写得很快,所以请大家改进这个功能!

ps 现在该函数返回一个字符串值,所有索引用逗号分隔,您可以简单地对其进行编辑以返回一个对象

于 2013-04-19T10:49:40.503 回答
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));
于 2013-04-19T12:16:56.803 回答
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
于 2020-04-05T16:06:52.060 回答
0

ES6 使这变得相当容易。

function findIndexOfNestedArray(nestedArray, searchArray) {
  return searchArray.findIndex(item => {
    return item.length === nestedArray.length
    && item.every((a, i) => a === nestedArray[i])
  })
}
于 2021-04-16T12:23:54.657 回答
0

复制并粘贴此代码

< masterArray > 替换为您的主数组(嵌套所有其他数组的那个)

代码:

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

我一直在寻找一种解决方案来删除数组中的数组,并提出了这个丑陋但富有成效 的解决方案:使用数组数组(两次),但没有进一步或更深的嵌套。

此代码会将嵌套数组转换为字符串 => 将一个一个记录到一个临时数组中 => 每次记录时比较当前记录的字符串是否已经在数组中。如果重复,则从masterArray(您的)和 stringArray中删除元素

于 2021-04-20T06:22:16.023 回答