发现在JavaScript二维数组的第二个元素的最大值 [英] find max of second element of two dimension array in javascript

查看:196
本文介绍了发现在JavaScript二维数组的第二个元素的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组称为标记这是两个如下维和展示学生证和标志:

 标记= [
    [1100]
    [1150]
    [1,80]
    [2100]
    [1300]
    [2250]
]

我要建立与学生的ID和MAX标记如下数组:

 的结果:
    [1300]
    [2250]
]


解决方案

一个最简单的方法是使用对象的键/值对创建一个临时存储空间,而你循环数组。设置每个内部阵列作为对象键的第一个元素,并将其添加到该值,如果其值比已经存在的值。然后,只需将其导出为一个数组。

 函数的getResult(ARR){    //创建用于存储的临时对象
    变种TMP = {};    //通过数组元素循环
    对于(VAR I = 0,1 = arr.length; I<升;我++){        //键/值设置为第一和第二值
        //迭代数组元素
        VAR键=改编[I] [0];
        VAR值=改编[I] [1];        //如果该键不存在于物体存在
        //它设置为零
        如果{TMP [关键] = 0(TMP [关键]!); }        //如果该值大于当前值的
        //更改对象的值
        如果(价值> TMP [关键]){TMP [关键] =价值; }
    }    //使用`map`遍历对象键和
    //创建成果的数组
    //添加+ el`胁迫的对象密钥字符串前`
    //成整数
    返回Object.keys(TMP).MAP(功能(EL){
      返回[+ EL,TMP [EL]];
    });}的getResult(标记); // [[1,300],[2,250]]

演示

I have got an array called mark which is two dimensional as below and shows student id and mark:

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

I am going to create an array with students id and max mark as below:

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

解决方案

One of the easiest way is to use the key/value pairs of an object to create a temporary storage space while you loop over the array. Set the first element of each inner array as the object key and add it to the value if its value is greater than the value that already exists. Then just export it as an array.

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

这篇关于发现在JavaScript二维数组的第二个元素的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆