Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
769 views
in Technique[技术] by (71.8m points)

find max of second element of two dimension array in javascript

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]
]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...