kuldarim - 2 years ago 76
Javascript Question

# Order array by predefined rules

I have an array of currencies

`["GBP", "EUR", "NOK", "DKK", "SKE", "USD", "SEK", "BGN"]`
. I would like to order it by moving predefined list if the currency is present to the beginning of array. Predefined list is
`['EUR', 'USD', 'DKK', 'SKE', 'NOK', 'GBP']`
.
So in this case it should return
`['EUR', 'USD', 'DKK', 'SKE', 'NOK', 'GBP', 'SEK', BGN']`
.

But in case unfiltered array does not contain all values in predifined list it should also order it correctly. For example :
`["GBP", "EUR", "NOK", "LTU", "ZGN"]`
should look like
`['EUR', 'NOK', 'GBP', 'LTU', 'ZGN'`

I was trying to sort it using this function:

``````list.sort(c => ['EUR', 'USD', 'DKK', 'SKE', 'NOK', 'GBP'].indexOf(c))
``````

but it puts all predefined currencies at the end of the list, not at the from. Maybe there is a better way of doing that?

You could use sorting with map and a hash table for the sort order. If the value is not in the hash table, the original order is taken.

``````var order = ['EUR', 'USD', 'DKK', 'SKE', 'NOK', 'GBP'],
orderObj = Object.create(null),
data = ["GBP", "EUR", "NOK", "DKK", "SKE", "USD", "SEK", "BGN"];

// generate hash table
order.forEach((a, i) => orderObj[a] = i + 1);

// temporary array holds objects with position and sort-value
var mapped = data.map((el, i) => { return { index: i, value: orderObj[el] || Infinity }; });

// sorting the mapped array containing the reduced values
mapped.sort((a, b) => a.value - b.value || a.index - b.index);

// assigning the resulting order
var data = mapped.map(el => data[el.index]);

console.log(data);``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download