Sort an array, get the lowest three values and return the labels from those values

I've got this array with different labels and always different values.
I would like to have the three lowest values and return the labels in from of those values.
I'm searching my *ss off but JS and other code programming is not my cup of tea.
I've tried converting it to a CSV in Node-RED and tried to select the MIN value but I get only one value and I would like have three off them.

Is there a simple solution for this? Or is this not possible with this structure of the array?

To return the lowest 3 labels try

delete msg.payload[0].datum;
let output = Object.entries(msg.payload[0])
output = output.sort((a,b) => a[1]- b[1]).slice(0,3); // sort and select lowest 3
msg.payload = output.map(arr => arr[0]) //return key only
return msg;
1 Like

Well thank you! You are my life saver!
When I want to sort it for the highest is this the right code?

delete msg.payload[0].datum;
let output = Object.entries(msg.payload[0])
output = output.sort((b,a) => a[1]- b[1]).slice(0,3); // sort and select lowest 3
msg.payload = output.map(arr => arr[0]) //return key only

Thanks a lot

Have you tested it, it should work

or in original example you can slice(-3) for last 3 which should be the highest.
It really depends on how you want the 3 keys returned, low to high or high to low.

After some fiddeling around I managerd to get both formulas work:

let output = Object.entries(msg.payload[0])
output = output.sort((a,b) => a[1]- b[1]).slice(0,3); // sort and select lowest 3
msg.payload = output.map(arr => arr[0]) //return key only
let output = Object.entries(msg.payload[0])
output = output.sort((b,a) => b[1]- a[1]).slice(-3); // sort and select highest 3
msg.payload = output.map(arr => arr[0]) //return key only

Again, thank you!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.