简体   繁体   中英

How to custom sort a one dimensional javascript array by key

I have a javascript array looking like this:

[USD: -119, EUR: 217, TRY: -401, GBP: 200, AED: 700]

And I want to sort it as below:

[USD: -119, TRY: -401, EUR: 217, AED: 700, GBP: 200]

Keeping in mind that these arrays are created dynamically, so some of them can have no GBP for example or EUR, or in one array for example EUR can appear at 3th place or at the end.

You can first create an array with the desired order. Then you use the sort function. To compare elements, compare which has the higher/lower index in the sortOrder array.

 const sortOrder = ['USD', 'TRY', 'EUR', 'AED', 'GBP'] const data = [['USD', -119], ['EUR', 217], ['TRY', -401], ['GBP', 200], ['AED', 700]] console.log(data.sort((a, b) => sortOrder.indexOf(a[0]) - sortOrder.indexOf(b[0])))

I don't think there is any comparison logic, this is not sorting, this is basically the order you want specifically in the array.

I'd suggest creating a new array, checking if an item of the specific location exists, if yes, add it to the new array.

This is crucial if you say that keys are created dynamically, and there is no prior knowledge of the contents of the array.

let oldArray = {USD: -119, EUR: 217, TRY: -401, GBP: 200, AED: 700};
let newArray = {};
if (oldArray['USD']) {
    newArray['USD'] = oldArray['USD'];    
}
if (oldArray['TRY']) {
    newArray['TRY'] = oldArray['TRY'];
}
if (oldArray['EUR']) {
    newArray['EUR'] = oldArray['EUR'];
}
if (oldArray['AED']) {
    newArray['AED'] = oldArray['AED'];
}
if (oldArray['GBP']) {
    newArray['GBP'] = oldArray['GBP'];
}
console.log(newArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM