0
var global=[];
var value=[50,1,4,29];
var title=["d","b","c","a"];

title.forEach(function(title,i) {
    global[title]=value[i];
})

I would like to sort the global array by value but I can't figure out how.

I precise I can't use any library jquery,underscore...

thanks !

the goal is to know what object has the less value. a,b,c,d have values 50,1,4,29

I can sort values but how to know what's the name associated to this value ?

François Richard
  • 6,817
  • 10
  • 43
  • 78

1 Answers1

0

You're not using global[] correctly as an array in your loop. You can't reference array items with [title], you can either push to the array global.push(value[i]) or use global[i] = value[i]. If you use either of these methods you can just call 'global.sort()' to sort the array which will give you [1, 29, 4, 50]. If you want to use the array as multidimensional, you need to change your loop to something like this:

title.forEach(function(title,i) {
    global[i] = {};
    global[i][title]=value[i];
})

which will give you [Object { d=50}, Object { b=1}, Object { c=4}, Object { a=29}]

If you want to sort this you could use sort which takes a function in which you can write your custom sorter but I don't think you can use this as all your keys are different. If all your keys were the same, say 'value' ,i.e [Object { value=50}, Object { value=1}, Object { value=4}, Object { value=29}] , you could do:

global.sort(function(a,b) {
    return parseInt(a.value, 10) - parseInt(b.value, 10);
});

but this can't be applied to your array since all the keys are different.

artm
  • 8,554
  • 3
  • 26
  • 43
  • well thanks but how could I address this problem ? it seems a really simple problem but I can't figure it out how to resolve it simply. – François Richard Oct 26 '14 at 10:12
  • I thought it was a clear answer, what part are you having problems understanding with? – artm Oct 26 '14 at 11:31