在索引数组上找到最大值

时间:2018-10-01 15:14:03

标签: javascript arrays

我必须找到数组的最大值并返回其索引位置。

这是我的代码段:

function findGreaterNumbers(array) {
    for(var i = 1; i < array.length; i++) {
        if(array[i].length !== 0) {
            var result = Math.max.apply(null, [i]);
        } else {
            return 0;
        }
    }
    return result;
}
console.log(findGreaterNumbers([1, 2, 3]);        // 2: I want 3
console.log(findGreaterNumbers([6, 1, 2, 7]));    // 3: I want 4
console.log(findGreaterNumbers([5, 4, 3, 2, 1])); // 4: I want 0
console.log(findGreaterNumbers([]));              // undefined: I want 0 

6 个答案:

答案 0 :(得分:0)

const input = [1,5,3,4,0,-1];
function getMaxIndex() {
  const max = Math.max(...input);
  return input.findIndex((item) => item === max);
}

console.log(getMaxIndex())

答案 1 :(得分:0)

尝试一下!

function findGreaterNumbers(arr) {
    let count = 0;
    for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if (arr[i] < arr[j]) {
                count ++;
            }
        }
    }
    return count;
}

findGreaterNumbers([1,2,3]) // 3
findGreaterNumbers([6,1,2,7]) // 4
findGreaterNumbers([5,4,3,2,1]) // 0
findGreaterNumbers([]) // 0

答案 2 :(得分:0)

尝试并尝试一些简单的事情:

invalidateIntrinsicContentSize()

更多说明:forEach

答案 3 :(得分:0)

您可以通过Math.max查找最大数量并从Array.indexOf查找最大索引的另一种方式

var numbers = [ 0, 1, 3, 2, 5, 10 , 4 ,6];

var max = Math.max(...numbers)

var index = numbers.indexOf(max)

console.log('Index of max', index)

答案 4 :(得分:0)

您可以执行以下操作:

const findMax = (arr) => {
    const max = Math.max.apply(Math, arr);
    return arr.indexOf(max);
}

首先创建一个接收数组arr的函数,然后在该函数内部使用Math.max内置的JS方法找到具有最高值的数组元素。如果返回此值,则将显示您提供的数组中数字的最大值。

为了返回索引,可以使用indexOf数组方法找到其索引。您返回此值,就可以得到数组中最大数目的索引。

答案 5 :(得分:0)

对于非常有用的数组,我会使用内置的mapreduce方法。 map将一个数组转换为另一个相同长度的数组,而reduce可用于对该数组本身进行任何聚合。找到最低/最高值只是一种特殊的聚合方式。

也就是说,以下方法将为您提供与最大值对应的所有索引:

function iMax(array) {
    return array.reduce((m, d, i) => {
        return (m.length === 0 || d > m[0].d)
            ? [{d: d, i: i}]
            : (d === m[0].d ? m.concat({d: d, i: i}) : m)
    }, [])
        .map(d => d.i);
}

// Run tests
console.log(JSON.stringify([1, 2, 3]) + " => " + JSON.stringify(iMax([1, 2, 3])));
console.log(JSON.stringify([6, 1, 2, 7]) + " => " + JSON.stringify(iMax([6, 1, 2, 7])));
console.log(JSON.stringify([5, 4, 3, 2, 1]) + " => " + JSON.stringify(iMax([5, 4, 3, 2, 1])));
console.log(JSON.stringify([5, 4, 3, 5, 2, 1]) + " => " + JSON.stringify(iMax([5, 4, 3, 5, 2, 1])));
console.log(JSON.stringify([]) + " => " + JSON.stringify(iMax([])));

我还添加了一个具有多个最大值的示例。请注意,Javascript中的索引以0开头,如果您需要示例中提到的索引,则可以将1添加到结果中(但我不建议这样做)。最后,如果在输入数组中没有最大值的情况下,如果需要除空数组之外的任何其他值,则可以在返回结果之前使用if

相关问题