返回数组javascript中的两个最高数字

问题描述 投票:0回答:1

编写一个名为twoHighest的函数,该函数将一个数字数组作为其参数,并返回该数组中的两个最高数字。

返回的值应该是以下格式的数组:[secondHighest,最高]

传递的数字顺序可以是任何顺序。

请不要使用build in sort()方法-测试将失败!

function twoHighest(arr){
  var highest = 0;
  var secondHighest= 0;

    for(i=0; i<arr.length; i++){
      if(arr[i] > highest){
      highest = arr[i];
  }
}
    for(i=0; i<arr.length; i++){
      if(arr[i] > secondHighest && arr[i] < highest){
      secondHighest = arr[i]; 
    }
  }
    return [secondHighest, highest];
}

// twoHighest([1, 2, 10, 8]); // [8, 10]
// // twoHighest([6, 1, 9, 10, 4]); // [9,10]
// // twoHighest([4, 25, 3, 20, 19, 5]); // [20,25]
twoHighest([1, 2, 2]) // [2, 2];

此操作直到最后一个数组[1,2,2]。它返回的是[1,2],而不是[2,2]。

javascript
1个回答
0
投票

我将您的功能重构为更可重用的功能:

const findHighest = (input, depth, result = [], iteration = 1) => {
        if(!input.length) {
            return result;
        }
        highest = input[0];
        highestIndex = 0;
        if(input.length === 1) {
            return [...result, highest];
        }
        for(let i = 1; i < input.length; i++) {
            if(input[i] > highest) {
                highest = input[i];
                highestIndex = i;
            }
        }
        input.splice(highestIndex, 1);
        result = [...result, highest];
        if(iteration === depth) {
            return result;
        } else {
            return findHighest(input, depth, result, iteration + 1);
        }
    }

    console.log(findHighest([1,2,2], 2)); // returns [2,2]
© www.soinside.com 2019 - 2024. All rights reserved.