Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...