Node.js,找到最大的一对

时间:2019-03-17 04:31:21

标签: arrays node.js

对于Node.js,我该如何找到[“ 5”,0.668574],以下是最大的代码:

[[[[“ 0”,0.0137134],[“ 1”,0.0156018],[“ 2”,0.142732],[“ 3”,0.14874],[“ 4”,0.0151308],[“ 5”, 0.668574]]]

谢谢!

Finally figured out with the help of Piyush N. Thanks Community !

var pairs = [[["0",0.0137134],["1",0.0156018],["2",0.142732],["3",0.14874],["4",0.0151308],["5",0.668574]]];

var max = ((pairs [0])[0])[1];
var maxPair = (pairs [0])[0];  
pairs[0].forEach(pair => {
    if(pair[1] > max) {
    max = pair[1];
    maxPair = pair;
  }
});

console.log(maxPair);

2 个答案:

答案 0 :(得分:0)

var pairs = [["0",0.0137134],["1",0.0156018],["2",0.142732],["3",0.14874],["4",0.0151308],["5",0.668574]];

var sumOfMaxPair = parseInt((pairs[0])[0]) + (pairs[0])[1];
var maxPair = pairs[0];

pairs.forEach(pair => {
  var sumOfCurrentPair = parseFloat(pair[0], 10) + pair[1];
  if(sumOfCurrentPair > sumOfMaxPair) {
    sumOfMaxPair = sumOfCurrentPair;
    maxPair = pair;
  }
});

console.log(maxPair);

答案 1 :(得分:0)

谢谢,皮尤什!这很有帮助!

我可能误导了您,一对中的第一个项目是字符串,我希望得到第二个中最大的项目。按照您的逻辑,我发现它如下,并且有效!

请注意,与您的原始变量对相比,原始变量对还具有一组[]。

var pairs = [[["0",0.0137134],["1",0.0156018],["2",0.142732],["3",0.14874],["4",0.0151308],["5",0.668574]]];

var max = ((pairs [0])[0])[1];
var maxPair = (pairs [0])[0];  
pairs[0].forEach(pair => {
    if(pair[1] > max) {
    max = pair[1];
    max = max;  
    maxPair = pair;
    maxPair = maxPair;
  }
});

console.log(maxPair);