Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

arrays - Javascript - How to find two elements with more value?

I have an array and I'm trying to get two of the highest values of the array, for example:

[1, 2, 3, 4, 3, 1, 0]

I need the return to be like this: [ 4, 3]

How can this be done? At the moment I have a function that returns me the max of the array only, (in this example, only [4]). But I need the highest and the second, if it repeats, like this example (3 appears two times), only one of them, to make an array of two elements.

My function at the moment:

    indexOfMax(arr) {  
    var max = -Infinity;
    var maxIndices = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === max) {
          maxIndices.push(i);
        } else if (arr[i] > max) {
            maxIndices = [i];
            max = arr[i];
        }
    }
    return maxIndices;

 },

Thanks for all the answers! You guys rock!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this using the sort function and get the two first values of the results

const sortedArray = [1, 2, 3, 4].sort((a, b) => {
  if(a < b) return 1

  return -1
})

sortedArray[0] // 4
sortedArray[1] // 3

// or

const [highest, secondHighest] = sortedArray

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...