1 回答
TA贡献1848条经验 获得超6个赞
你可以这样做:
循环遍历您的Matrix,通过将该行传递到函数中来找到该行的最小值 - 使用扩展语法(将数组项“解包”到函数参数中)。将此最小值放入数组中,或者将此最小值的索引放入数组中(或者您可以同时执行这两项操作)。Math.min()const min_val = Math.min(...u[row]);actact[row] = min_val;act[row] = u[row].indexOf(min_val);
如果您不需要所有最小值/索引(只需要按需给定的行),则可以使用底部的函数。
const ROWS = 100;
const COLS = 5;
const u = Array.from({ length: ROWS}, (v, i) => []);
//let's fill the Matrix:
for (let row = 0; row < u.length; row++){
for (let col = 0; col < COLS; col++){
u[row].push(Math.random());
}
}
console.log(u)
//Create an array of all min values/indexes:
const act = Array(u.length);
for (let row = 0; row < u.length; row++){
const min_val = Math.min(...u[row]);
//put min value in:
//act[row] = min_val;
//or put min value index in:
act[row] = u[row].indexOf(min_val);
//or you could do both:
//act[row] = [ min_val, u[row].indexOf(min_val) ];
}
console.log(act)
//if you just want to get any min index of any row on the fly use this function:
function getMinIndexAtRow(inputArr, row){
const min_val = Math.min(...inputArr[row]);
return u[row].indexOf(min_val);
}
//use it like this:
console.log(getMinIndexAtRow(u, 0));
添加回答
举报