0

I have an array of objects like so. I really don't know where to start with this which is why I've not posted any attempts. Even a nudge in the right direct would help a lot!

What I want is for my data to be sorted (based on a 50:50 weight) between humidity and temperature where the ideal (most top ranking) is 60 humidity and 40 temp.

This is my data;

Array[5]
  0: Object
    humidity: 65
    name: "HLLM"
    temp: 25
    __proto__: Object
  1: Object
    humidity: 61
    name: "LICD"
    temp: 27
    __proto__: Object
  2: Object
    humidity: undefined
    name: "EW3448"
    temp: 28
    __proto__: Object
  3: Object
    humidity: 42
    name: "HLLT"
    temp: 29
    __proto__: Object
  4: Object
    humidity: 30
    name: "LMML"
    temp: 30

Kind Regards, Harry

Harry Torry
  • 373
  • 5
  • 25
  • So, given the data you presented here, what would be the finished sorting order? I don't understand your sorting criteria/method. – Jonathan M Jun 12 '14 at 16:20
  • 1
    Here is a start: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Felix Kling Jun 12 '14 at 16:21
  • the above was the fourth result when I googled "sorting array in javascript" – Liam Jun 12 '14 at 16:22

1 Answers1

0

Use the javascript sort method with a function.

var data = [
  {
    humidity: 65,
    name: "HLLM",
    temp: 25
  },
  {
    humidity: 61,
    name: "LICD",
    temp: 27
  },
  {
    humidity: 70,
    name: "TEST",
    temp: 28
  }
]

data.sort(function(a, b) {
  // Takes the average of humidity and temperature
  // You can use some other system e.g. calculating absolute difference between 60 and 40 and so on
  return (a.humidity + a.temp) / 2 - (b.humidity + b.temp) / 2;
});

This will sort the data by lowest temperature/humidity to highest temperature/humidity.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

soktinpk
  • 3,778
  • 2
  • 22
  • 33
  • Is this really how the OP wants this sorted? I don't this so because he says humidity=60 and temp=40 should be top. This will put all humidity/temp combinations that total 100 on the same level. – Jonathan M Jun 12 '14 at 16:23