How to find the two lowest values of five values

Hi guys,

I have multiple msg.payloads and i want to pick out the two lowest values out for these.
I'm aware of the $min(payload) but this will only pick out the lowest value, I also want the second lowest value.

The use of the function will be to pick out the two lowest price hours and start an action with these values

I also have these input values as 'flow.get' values

If you put your flow variables into an array you can sort it. Then the two lowest values will be in array[0] and array[1]:

        "id": "839f8962b0f806b1",
        "type": "function",
        "z": "9372feccca70ce91",
        "name": "function 7",
        "func": "flow.set('h01', 0.75);\nflow.set('h02', 0.82);\nflow.set('h03', 0.72);\nflow.set('h04', 0.75);\nflow.set('h05', 0.91);\n\nvar myarray = [['h01', flow.get('h01')], ['h02', flow.get('h02')], ['h03', flow.get('h03')], ['h04', flow.get('h04')], ['h05', flow.get('h05')]];\nmsg.payload = myarray.sort((a,b) => a[1] - b[1])\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 420,
        "y": 120,
        "wires": [

Great! Thank you :slight_smile:

JUst for info, the context can be fetched as an array.

let output = flow.get(["h01","h02","h03","h04","h05"]).sort((a,b) => a - b);
msg.payload = output; //msg.payload[0] is lowest  msg.payload[1] is next lowest etc
return msg;

That's much nicer code than my back of an envelope attempt @E1cid but although it sorts the values, it loses the association with the hour number.

If the OP wants association then

const flow_var_keys = ["h01","h02","h03","h04","h05"];
let output = flow.get(flow_var_keys).
    map((value, index) => { return {"flow_var": flow_var_keys[index], value}}).
    sort((a,b) => a.value - b.value);
msg.payload = output;
return msg;

Sometimes some values are exact same. And most of the times it doesn't really matter. But sometimes it does.
Just saying cos most of the times that little edge case isn't even considered.

Thank you all for your examples, it helped me!

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