【问题标题】:find max of second element of two dimension array in javascript在javascript中找到二维数组的第二个元素的最大值
【发布时间】:2015-06-16 12:04:15
【问题描述】:

我有一个名为 mark 的数组,它是二维的,如下所示,显示学生 id 和 mark:

mark =   [
    [1,100],
    [1,150], 
    [1,80],
    [2,100],
    [1,300],
    [2,250]
]

我将创建一个包含学生 ID 和最大标记的数组,如下所示:

result: [
    [1,300],
    [2,250]
]

【问题讨论】:

  • Stack Overflow 不是代码编写服务。向我们展示您的尝试,以及您遇到的问题。
  • 您能详细说明一下吗?
  • 亲爱的 Oka,这是我代码的一小部分,我将我的问题简化为它。我正在寻找提示。

标签: javascript arrays


【解决方案1】:

最简单的方法之一是在遍历数组时使用对象的键/值对来创建临时存储空间。将每个内部数组的第一个元素设置为对象键,如果其值大于已存在的值,则将其添加到值中。然后将其导出为数组。

function getResult(arr) {

    // create a temporary object for storage
    var tmp = {};

    // loop through the array elements
    for (var i = 0, l = arr.length; i < l; i++) {

        // set the key/values to the first and second values of
        // of the iterated array element
        var key = arr[i][0];
        var value = arr[i][1];

        // if the key doesn't exist in the object
        // set it to zero
        if (!tmp[key]) { tmp[key] = 0; }

        // if the value is greater than the current value
        // change the value of the object
        if (value > tmp[key]) { tmp[key] = value; }
    }

    // use `map` to iterate over the object keys and
    // create an array of results
    // adding + before `el` coerces the object key string
    // into an integer
    return Object.keys(tmp).map(function (el) {
      return [ +el, tmp[el] ];
    });

}

getResult(mark); // [ [1, 300], [2, 250] ]

DEMO

【讨论】:

  • 谢谢,很有帮助
【解决方案2】:

盖住你的“标记”标签。

对于每个元素,

if(mark[i][1] > result[mark[i][0]])
    result[mark[i][0]] = mark[i][1]

您在这样的对象中得到了结果

results = {
   1: 300,
   2: 250
}

【讨论】:

  • 这个结果可以像一个带有循环的数组一样被覆盖:“for (var id in results) { results[id] // done the mark for id }”
【解决方案3】:

您可以将array.sort() 函数与custom compare function 一起使用,最大值将是结果中的第一个元素:

mark = [[1,100], [1,150], [1,80], [2,100], [1,300], [2,250]];

mark.sort(function(a,b){
    return b[1] - a[1];
});

console.log(mark);

此函数将根据内部数组的第二项的值对数组进行降序排序。您可以通过将b[1] - a[1] 更改为a[1] - b[1] 将其更改为升序

jsfiddle

【讨论】:

    猜你喜欢
    • 2019-08-28
    • 2021-02-18
    • 1970-01-01
    • 2014-09-18
    • 2022-01-22
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    相关资源
    最近更新 更多