gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:38:29 28 4
gpt4 key购买 nike

我有一个这样的数组:

[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"

最佳答案

这是我的方法。它将所有数组展平为更易于管理的数组,找到最大数字及其索引,然后使用一些数学计算其位置。使用单个数组使计算变得更加容易。

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

关于javascript - 使用 JavaScript 返回 3 维数组中最大值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57903163/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com