开发者

Javascript - arrays sorting

开发者 https://www.devze.com 2023-04-03 21:16 出处:网络
I have two arrays: keys_array= [2,4,5,8,9] values_array = [\'two\',\'four\',\'five\',\'eight\',\'nine\']

I have two arrays:

keys_array   = [2,4,5,8,9]
values_array = ['two','four','five','eight','nine']

I need to get:

#transitional result
#values sorted alphabetically
sorted_by_value_name_array = [
  ['8','eight'],
  ['5','five'],
  ['4','four'],
  ['9','nine'],
  ['2','two']
]

#final result  
sorted_keys_array = [8,5,4,9,2]

How can i achieve this wit开发者_如何学运维h javascript or jQuery?


var keys_array   = [2,4,5,8,9];
var values_array = ['two','four','five','eight','nine'];
var new_array = [];
for(var i=0; i<keys_array.length; i++){
    new_array.push([keys_array[i],values_array[i]]);
}

console.log(new_array.sort(function(a,b){ return a[1] < b[1] ? -1 : 1; }));


The answer by Andy is great, but what if your keys and values are not fully aligned? Then you'll need JavaScript to be able to interpret strings into numbers.

I found a working words to numbers converter by Stephen Chapman. By utilizing this in another function we can have more or less any numerical words and combine these with the corresponding number. And they don't even have to be aligned in the first place.

// paste the toWords function here
function naturalCombine(numbers, words) {
    var numberCount = numbers.length,
        combined = [];
    for (var i=0; i < numberCount; i++) {
        var word = toWords(numbers[i]).trim(),
            found = words[words.indexOf(word)];
        if (found)
            combined.push([numbers[i], found]);
        else
            combined.push([numbers[i], "unknown"]);
    }
    return combined;
}

var keysArray = ["4", "62", "2", "94", "5", "9", "8", "87", "1674"];
var valuesArray = ["two", "one thousand six hundred seventy four", "four", 
                   "five", "eight", "nine", "eighty seven", "ninety four"];

var combined = naturalCombine(keysArray, valuesArray);

Check test case on jsFiddle


var keys_array = [2,4,5,8,9],
    values_array = ['two','four','five','eight','nine'];

var svalues = values_array.slice().sort(), // copy array and sort it
    skeys = [];

for(var i = 0, s = svalues.length; i < s; i++){
    skeys.push(keys_array[values_array.indexOf(svalues[i])]);
}

Demo

You will need to extend the array prototype with indexOf() for it to work with browsers which do not support it.

0

精彩评论

暂无评论...
验证码 换一张
取 消