3 回答
TA贡献1827条经验 获得超8个赞
一个简单的解决方案是遍历数组并将最小值/最大值存储在临时变量中。
function minMax (arr, n) {
let min=Infinity, max=0;
for (const _arr of arr) {
const x = _arr[n];
if (x < min) min = x;
if (x > max) max = x;
}
return [min, max];
}
function minMaxIndex (arr, n) {
let min=Infinity, max=0, minIndex, maxIndex;
for (let i=0; i < arr.length; i++) {
const x = arr[i][n];
if (x < min) {
min = x;
minIndex = i;
}
if (x > max) {
max = x;
maxIndex = i;
}
}
return [minIndex, maxIndex];
}
console.log (minMax(a, 0))
console.log (minMaxIndex(a, 0))
<script>
a = [
[22,23],
[74,1],
[21,33],
[32,84],
[11,31],
[1,49],
[7,8],
[11,11],
[99,68],
[52,20]
];
</script>
TA贡献1815条经验 获得超10个赞
你快到了,你只关心性能,对吧?因此,为了提高程序的性能,您可以使用一种名为Memoization
记忆是一种优化技术,主要用于通过存储昂贵的函数调用的结果并在再次出现相同的输入时返回缓存的结果来加速计算机程序
const arr = [[22,23], [74,1], [21,33], [32,84], [11,31], [1,49], [7,8], [11,11], [99,68], [52,20]];
/**
* Here I create the momoized function which cache the
* column and if we want to get the same column then it
* simply return the previously cached column array
* otherwise, it get the column and cache it for future
* and return it.
*/
const memoized = () => {
const cache = {};
return (arr, index) => {
if (index in cache) {
return cache[index];
} else {
const col = arr.map(item => (item[index]));
cache[index] = col;
return col;
}
}
}
/**
* As memoized is a higher order function so it returns
* another function which will be executed by calling
* this getColumn function reference.
*/
const getColumn = memoized();
const getMinValue = (arr, col) => Math.min(...getColumn(arr, col));
const getMaxValue = (arr, col) => Math.max(...getColumn(arr, col));
const minValueIndex = (arr, col) => getColumn(arr, col).indexOf(getMinValue(arr, col));
const maxValueIndex = (arr, col) => getColumn(arr, col).indexOf(getMaxValue(arr, col));
console.log('minValue: ', getMinValue(arr, 0)); // Calculated
console.log('maxValue: ',getMaxValue(arr, 0)); // Cached
console.log('minValueIndex: ', minValueIndex(arr, 0)); // Cached
console.log('maxValueIndex: ', maxValueIndex(arr, 0)); // Cached
.as-console-wrapper {min-height: 100% !important; top: 0;}
TA贡献1828条经验 获得超13个赞
这会有帮助吗?
let a = [
[22, 23],
[74, 1],
[21, 33],
[32, 84],
[11, 31],
[1, 49],
[7, 8],
[11, 11],
[99, 68],
[52, 20]
];
let max = 0,
min = 0,
minIndex = 0,
maxIndex = 0;
const findValue = (array, col) => {
array.map((matrix) => {
(matrix[col] > max) ? max = matrix[col]: null;
(min == 0) ? min = max: null;
(matrix[col] < min) ? min = matrix[col]: null;
})
}
const findIndex = (array, col, min, max) => {
minIndex = array.map(data => data[col]).indexOf(min);
maxIndex = array.map(data => data[col]).indexOf(max);
}
findValue(a, 0)
findIndex(a, 0, min, max);
console.log(min, max, minIndex, maxIndex);
添加回答
举报
