djecko
djecko

Reputation: 43

How to sort an associative array by sort function in Javascript with the same ID?

function updateUld(pUldValues){
    if (pUldValues != null){
        pUldValues.sort(compareSort);
    }
}

function compareSort (first,second){
    var ret = 0;
    var uldA = first[1]; //TOTO
    var UldB = second[1]; //MAMA
      if (uldA.substring(0,1) == "T"){
            ret = compareRefUldRefUldTULD(uldA, UldB);
        }
        if (uldA.substring(0,1) == "M" ||
                uldA.substring(0,1) == "A"){
            ret = compareRefUldRefUldMix(uldA, UldB);
        }
        if (uldA.substring(0,1) == "L"){
            ret = compareRefUldRefUldLoose(uldA, UldB);
        }
        if(ret==0){
            if (UldB.substring(0,1) == "M" ||
                    UldB.substring(0,1) == "A"||
                    UldB.substring(0,1) == "T" ||
                    UldB.substring(0,1) == "L"){
                ret = -1 ; 
            }else{
                ret= UldB.localeCompare(uldA);
            }
        }
        return -ret ;
}

pUldValues before sort contains 555 : MAMA + 556 : TOTO ...

After sort is : 0 : TOTO + 1 : MAMA ...

I would like that I have the same sorted but in this format : 555 : TOTO + 556 : MAMA

Upvotes: 1

Views: 58

Answers (1)

Techniv
Techniv

Reputation: 1967

You can't use an Array as a Map and you can't order an Object.

But since ECMAScript 2015 you can use the Map object which guarantees the order of the keys. See the Map documentation

Here a rapid exemple with an object in input:

var myMap = {
  "555":  "TOTO",
  "556":  "MAMA",
  "557":  "PAPA",
  "1":    "ZOE",
  "2":    "ABC"
};

function sortMap(map){
	// Get the keys of map
	var keys= Object.keys(map);
	
	// Sort the keys by the value
	keys.sort(function(a,b){
		var aValue = map[a];
		var bValue = map[b];
		
		if(aValue < bValue) return -1;
		if(aValue > bValue) return 1;
		return 0;
		
	});
	
	// Rebuild the map from the sorted key.
	var result = new Map;
	for(var i = 0; i < keys.length; i++){
		result.set(keys[i], map[keys[i]]);
	}
	
	return result;
}

var sortedMap = sortMap(myMap);

// Snipet display
sortedMap.forEach(function(value, key){
  document.body.appendChild(document.createElement('div')).innerHTML = key+'=>'+value;
});

Upvotes: 1

Related Questions