Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Top values in the object, displayed with keys, javascript

I'm able to successfuly find out the largest values in the object, however. There is a problem, and that is inability to display the associated key with that value.

var obj = {
    t1: 1,
    t2: 33,
    t3: 10,
    t4: 9,
    t5: 45,
    t6: 101
    //...
}

// create an array
var arr = [];

// loop through the object and add values to the array
for (var p in obj) {
  arr.push(obj[p]);
}

// sort the array, largest numbers to lowest
arr.sort(function(a,b){return b - a});

// grab the first 10 numbers
var firstThree = arr.slice(0, 3);
console.log(firstThree);

It can display the top values, however i'm having a hard time to display keys with that.

The result should be like

var result = {
    t6: 101,
    t5: 45,
    t2: 33

}
like image 332
Stas Avatar asked Dec 07 '22 12:12

Stas


1 Answers

You could get the entries, sort and slice them and build a new object by assigning mapped objects to a single object.

var object = { t1: 1, t2: 33, t3: 10, t4: 9, t5: 45, t6: 101 },
    result = Object.assign(                      // collect all objects into a single obj
        ...Object                                // spread the final array as parameters
            .entries(object)                     // key a list of key/ value pairs
            .sort(({ 1: a }, { 1: b }) => b - a) // sort DESC by index 1
            .slice(0, 3)                         // get first three items of array
            .map(([k, v]) => ({ [k]: v }))       // map an object with a destructured
    );                                           // key/value pair

console.log(result);
like image 123
Nina Scholz Avatar answered Dec 31 '22 02:12

Nina Scholz