使用地图函数从2d数组获取行和列索引

问题描述 投票:0回答:2

我正在尝试使用map函数从2D数组中获取元素的行和列索引。

这是我的代码-

function getIndex() {
  var values = [['a', 'f', 'k', 'p', 'u'], ['b', 'g', 'l', 'q', 'v'], ['c', 'h', 'm', 'r', 'w'], ['d', 'i', 'n', 's', 'x'], ['e', 'j', 'o', 't', 'y']];
  var output = values.map(function (row, rowIndex) {
    return row.map(function (col, colIndex) {
      if (col == 's') {
        return values[rowIndex][colIndex];
      }
    })
  });
  console.log(output);
}

这是我最后运行它时得到的输出-

[[null, null, null, null, null], [null, null, null, null, null], [null, null, null, null, null], [null, null, null, s, null], [null, null, null, null, null]]

我不打算使用for循环,因为对于我正在处理的数据集而言,这不是最佳选择。需要在JavaScript数组中使用mapreducefilter函数。请帮助!

注意:我只需要行和列Index两者,而不需要实际值。

javascript
2个回答
0
投票

当遍历行时,请使用.findIndex,这样,如果回调返回真实值,则可以在外部使用索引。遍历列时,使用indexOf检查要查找的值是否存在于数组中-如果存在,将其分配给外部变量,将return true分配给findIndex

const rows = [
  ['a', 'f', 'k', 'p', 'u'],
  ['b', 'g', 'l', 'q', 'v'],
  ['c', 'h', 'm', 'r', 'w'],
  ['d', 'i', 'n', 's', 'x'],
  ['e', 'j', 'o', 't', 'y']
];
let colIndex = -1;
const rowIndex = rows.findIndex((row) => {
  const foundColIndex = row.indexOf('s');
  if (foundColIndex !== -1) {
    colIndex = foundColIndex;
    return true;
  }
});
console.log(rowIndex, colIndex);

如果未找到任何内容,则两个值均为-1。

如果您的环境非常古老,不支持ES6功能,那么您可以首先对其进行填充:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex#Polyfill


0
投票

您可以尝试这个

const rows = [
  ['a', 'f', 'k', 'p', 'u'],
  ['b', 'g', 'l', 'q', 'v'],
  ['c', 'h', 'm', 'r', 'w'],
  ['d', 'i', 'n', 's', 'x'],
  ['e', 'j', 'o', 't', 'y']
];

function getIndexOfK(arr, k) {
  for (var i = 0; i < arr.length; i++) {
    var index = arr[i].indexOf(k);
    if (index > -1) {
      return [i, index];
    }
  }
}
console.log(getIndexOfK(rows, 's'));
© www.soinside.com 2019 - 2024. All rights reserved.