且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

发现在JavaScript二维数组的第二个元素的最大值

更新时间:2023-02-05 13:07:08

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

 函数的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