使用 JavaScript 返回 3 维数组中最大值的索引

我有一个这样的数组:


[34, 12, 56]

[100,125,19]

[30,50,69]

125 已经是最高值,它会返回索引 [1,1] 格式。意思是最高值 125 将返回第 1 行第 1 列


我能够使用此代码获取数组中的索引


var a = [0, 21, 22, 7, 12];

var indexOfMaxValue = a.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : 

iMax, 0);

document.write("indexOfMaxValue = " + indexOfMaxValue); // prints 

"indexOfMaxValue = 2"


蛊毒传说
浏览 187回答 3
3回答

ITMISS

这是我的方法。它将所有数组展平为更易于管理的数组,找到最大数量及其索引,然后使用一些数学计算它的位置。使用单个数组使这种计算变得更加容易。const arr = [[34, 12, 56], [100,125,19], [30,50,69]];const arr2 = [0, 21, 22, 7, 12];function findHighest(arr) {  // Get the number of columns  const cols = arr.length;  // Flatten out the arrays  const tempArr = arr.flatMap(el => el);  // Get the max number from the array  const max = Math.max.apply(null, tempArr);  // Find its index  const indexMax = tempArr.findIndex(el => el === max);  // Find the remainder (modulo) when you divide the index  // by the number of columns  const mod = indexMax % cols;  // Return the final array output  return [Math.floor(indexMax / cols), mod];}console.log(findHighest(arr))console.log(findHighest(arr2))

素胚勾勒不出你

这将提供预期的输出,但不确定是否是解决此问题的好方法:var arr = [&nbsp; &nbsp; [34, 12, 56],&nbsp; &nbsp; [100, 125, 19],&nbsp; &nbsp; [30, 50, 69]];var maxValue, maxIndex;arr.forEach((arr1, i) => {&nbsp; &nbsp; arr1.forEach((value, j) => {&nbsp; &nbsp; &nbsp; &nbsp; if (i == 0 && j == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxValue = value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxIndex = [i, j]&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (maxValue < value) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxValue = value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxIndex = [i, j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });});console.log("Max Number Index", maxIndex);

繁花如伊

如果你的意思是二维解决方案,试试这个。应该适用于动态长度数组这应该可以通过新的 forEach 扩展到新的维度[100,125,19],[30,50,69]];maxIndex = [-1, -1];maxElem = 0;input.forEach(function(arr, row) {&nbsp; &nbsp; console.error(row);&nbsp; &nbsp; arr.forEach(function(e, col) {&nbsp; &nbsp; if( maxElem <= e ) {&nbsp; &nbsp; &nbsp; &nbsp; maxElem = e;&nbsp; &nbsp; &nbsp; &nbsp; maxIndex = [row, col];&nbsp; &nbsp; }&nbsp; })})console.log(maxIndex)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript