Sort a hash ascending by value using sortBy in javascript

I used the sortBy function in the underscore.js library.

I have hash and I tried to sort it by value as follows:

var obj = {x: 2, y: 6, z: 1, q: 4};
_.sortBy(obj)

But the conclusion is as follows:

[1, 2, 4, 6]

But I need to sort it and return the keys with the value as follows:

{z: 1, x: 2, q: 4, y: 6}

How to return a sorted hash with sortBy?

I noticed that it sortByreturns a list of functions, so is there another good solution for hash sorting, or do I need to implement a return sorted hash function?

+4
source share
3 answers

@Ragnar. . .

function getSortedHash(inputHash){
  var resultHash = {};

  var keys = Object.keys(inputHash);
  keys.sort(function(a, b) {
    return inputHash[a] - inputHash[b]
  }).forEach(function(k) {
    resultHash[k] = inputHash[k];
  });
  return resultHash;
}

function getSortedHash(inputHash){
  var resultHash = {};

  var keys = Object.keys(inputHash);
  keys.sort(function(a, b) {
    return inputHash[a] - inputHash[b]
  }).reverse().forEach(function(k) {
    resultHash[k] = inputHash[k];
  });
  return resultHash;
}
0

JavaScript , (). , , .

var keys = Object.keys(obj);
keys.sort(function(a, b) {
    return obj[a] - obj[b]
});

keys.forEach(function(k) {
   console.log(obj[k]);
});
+4

In addition, if you want to return the array in descending order, you can use the function reverse():

var obj = {x: 2, y: 6, z: 1, q: 4};

var keys = Object.keys(obj);
keys.sort(function(a, b) {
    return obj[a] - obj[b]
}).reverse().forEach(function(k) {
   console.log(obj[k]);
});

or just like that (thanks @muistooshort):

var obj = {x: 2, y: 6, z: 1, q: 4};

var keys = Object.keys(obj);
keys.sort(function(a, b) {
    return obj[b] - obj[a]   //inverted comparison
}).forEach(function(k) {
   console.log(obj[k]);
});
+1
source

Source: https://habr.com/ru/post/1614776/


All Articles