How to create custom ordering?

2

I'm looking for a way to create a custom computer.

Let's say I have the following:

var array = [
    1=>'A',
    2=>'B',
    3=>'C',
    4=>'D',
    5=>'E',
    6=>'F',
]

Now instead of sorting by index or value in alphabetical order or the reverse, I would like to pass my own order. It could be anything the user imagines ex:

  

ordem = acebdukl
ordem = brvdencst

If the array item does not exist in the order, it should go to the end. If the array item is repeated all the reps must be in sequence.

The example language does not matter, I just care about developing the idea.

    
asked by anonymous 30.06.2015 / 13:49

2 answers

2

I think this is what you're looking for: (example with array)

var array = [
    [1, 'A'],
    [2, 'B'],
    [3, 'C'],
    [4, 'D'], [4, 'D'],
    [5, 'E'],
    [6, 'F']
];

function ordenarPor(arr, ordem) {
    return arr.sort(function (a, b) {
        var indexA = ordem.indexOf(a[1].toLowerCase());
        var indexB = ordem.indexOf(b[1].toLowerCase());
        if (indexA < 0) indexA = arr.length + 1;
        if (indexB < 0) indexB = arr.length + 1;
        return indexA > indexB;
    });
}

var nova = ordenarPor(array, 'acebdukl');
console.log(JSON.stringify(nova));

// dá: [[1,"A"],[3,"C"],[5,"E"],[2,"B"],[4,"D"],[4,"D"],[6,"F"]]

jsFiddle: link

    
30.06.2015 / 14:05
1

In% with_%, these lines solve your problem:

string = 'acebdukl'

organizada = sum([list(filter(lambda key: key if key[1].upper() == letra else None, lista)) for letra in string.upper()], [])
organizada += [item for item in lista if item not in organizada]

print(organizada) 
>>>
[[1, 'A'], [3, 'C'], [5, 'E'], [2, 'B'], [4, 'D'], [4, 'D'], [6, 'F']]
    
30.06.2015 / 22:07