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 ?

2
  • 1
    Please show the expected result. Commented Oct 26, 2014 at 9:31
  • global isn't being used as an array. It's being used as an object (key-value store, map, hash table...) - hence, it's inherently unordered. Commented Oct 26, 2014 at 9:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
I thought it was a clear answer, what part are you having problems understanding with?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.