user3674148 user3674148 - 6 months ago 13
Javascript Question

JavaScript Dictionary reversal

I have a Dictionary which has 5 keys

var langDict = {};


IT-PL
EN
DE-FR
ZH-CH
IT-ES


I want the DE-FR to be in first position and EN in second position, others doesn't matter.

I am thinking to achieve this using a below recursive method but not getting the expected result.

for (var key in langDict) {
if (Object.keys(langDict).length > 0) {
langDict = filterKeys(langDict);
}
}

function filterKeys(langDict) {
for (var key in langDict) {
var langDictFiltered = {};
if (key.indexOf("DE") > -1) {
langDictFiltered[key] = langDict[key];
delete langDict[key];
break;
}
if (key.indexOf("EN") > -1) {
langDictFiltered[key] = langDict[key];
delete langDict[key];
break;
}
}

return langDict;
}

Answer

Objects have no special order, but you could take all keys of the object (Object.keys()) and take a custom sort with Array#sort and a hash table for the sort order.

Later you can use the array with the sorted key for populating.

var keys = ['IT - PL', 'EN', 'DE - FR', 'ZH - CH', 'IT - ES'];
keys.sort(function (a, b) {
    function value(v) {
        return { DE: 1, EN: 2 }[v.substring(0, 2)] || 10;
    }
    return value(a) - value(b);
});

document.write('<pre>' + JSON.stringify(keys, 0, 4) + '</pre>');

Edit

Version with splitting the strings and getting the most top value first.

var keys = ['IT-PL', 'EN', 'DE-FR', 'ZH-CH', 'IT-ES', 'EN-DE-FR-CH-PL'];
keys.sort(function (a, b) {
    function value(v) {
        return v.split('-').reduce(function (r, a) {
            return Math.min(r, { DE: 1, EN: 2 }[a] || 10);
        }, 10);
    }
    return value(a) - value(b);
});

document.write('<pre>' + JSON.stringify(keys, 0, 4) + '</pre>');

Comments