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 th
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);