-2

I have my data like this

enter image description here

I am trying to sort it like this

$initialArrayBTC.sort(function (a, b) {
    return b.q - a.q //Trying to sort is on the base of "q" in descending order
});

But this does not seem to work although I looked through many stackoverflow answers. Can anyone help me what might be the issue?

EDIT This is my all data inside the object

SAMPLE CODE

var $initialArrayBTC = [];
$initialArrayBTC['A'] = {
  q: "3598"
};
$initialArrayBTC['B'] = {
  q: "123"
};
$initialArrayBTC['C'] = {
  q: "9999"
};
console.log($initialArrayBTC);

$initialArrayBTC.sort(function(a, b) {
  return b.q - a.q //Trying to sort is on the base of "q" in descending order
});

console.log($initialArrayBTC);

enter image description here

connexo
  • 53,704
  • 14
  • 91
  • 128
Ali Zia
  • 3,825
  • 5
  • 29
  • 77

2 Answers2

2

You could build a new object by creating the properties in the wanted order, but this may works only with not integer numbers (numbers as indices for array) as keys and maybe not in all browsers.


You could take an object and then the keys of it, sort them and use the sorted keys for a sorted output.

var $initialArrayBTC = {};

$initialArrayBTC['A'] = {q: "3598"};
$initialArrayBTC['B'] = {q: "123"};
$initialArrayBTC['C'] = {q: "9999"};

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

keys.forEach(k => console.log($initialArrayBTC[k]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Looks like your initial instance is an object, as opposed to an array. You can grab its keys, sort the keys by values, then rebuild the object:

const $initialArrayBTC = {
  A: {q: '3598'}, 
  B: {q: '123'},
  C: {q: '9999'}
};

const result = Object.keys($initialArrayBTC)
  .sort((key1, key2) => $initialArrayBTC[key2].q - $initialArrayBTC[key1].q)
  .map(key => ({[key]: $initialArrayBTC[key]}));

console.log(result);
Jeto
  • 14,596
  • 2
  • 32
  • 46