1

Given

a = [{"a": 1}, {"b": 0}, {"w", -4}]

I want to rearrange this into

a = [{"w", -4},{"b": 0}, {"a": 1}]

Sort by lowest to greatest

Trying to do this with a.sort()

Sven.hig
  • 4,449
  • 2
  • 8
  • 18
third acc
  • 59
  • 3
  • Does this answer your question? [Sorting an array of objects by property values](https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values) – Mureinik Jul 19 '20 at 00:01
  • 1
    The “duplicate question”, while about sorting, relates to *known* property names. That is not the case here.. – user2864740 Jul 19 '20 at 00:04
  • Do you know the names of the variables that you want to sort on? – Charlie Wallace Jul 19 '20 at 02:11

3 Answers3

1

You could use sort() and Object.values

a = [{"a": 1}, {"b": 0}, {"w": -4}]
a.sort((a,b)=>Object.values(a)[0]-Object.values(b)[0])
console.log(a)
Sven.hig
  • 4,449
  • 2
  • 8
  • 18
  • Could you explain what the sort did? – third acc Jul 19 '20 at 00:01
  • it's minus, sort() takes 2 values and then when you want to sort your values in ascending order you do a-b and it will either return -1 or a positive value – Sven.hig Jul 19 '20 at 00:03
  • I have added a link if you want to read more about [sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – Sven.hig Jul 19 '20 at 00:06
  • 1
    It is a binary numeric subtraction and possibly an error as Object.values() returns an array. I would imagine the correction to be: “return Object.values(a)[0] - ..”, as indexing into the array will return the number. – user2864740 Jul 19 '20 at 00:06
  • 1
    Using `Array - Array` would not be the most common approach – charlietfl Jul 19 '20 at 00:08
0

Couln't you do it by passing by a map?

Maybe :

var map = new Map();

map.set("a", 1);
map.set("b", 0);
map.set("w", -4);
const sortedMapByValue= new Map([...map.entries()].sort((a, b) => a[1] - b[1]));

That normally gives you the result you want when iterating on sortedMapByValue

Edit: I haven't seen latest answer, pretty similar, better if you want to keep your array as is it

Handler
  • 194
  • 10
0

You could use sort with a custom comparator like so:

  a.sort(( a, b, o=Object.values ) => o(a)[0] - o(b)[0] )
rexfordkelly
  • 1,623
  • 10
  • 15