通过预定义的规则排序 [英] Order array by predefined rules

查看:161
本文介绍了通过预定义的规则排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列货币 [GBP,EUR,NOK,DKK,SKE,USD,SEK,BGN code>。如果货币存在于数组的开头,我想通过移动预定义的列表来订购它。预定义的列表是 ['EUR','USD','DKK','SKE','NOK','GBP']
所以在这种情况下,它应该返回 ['EUR','USD','DKK','SKE','NOK','GBP','SEK',BGN']

但是,如果未过滤的数组不包含预定列表中的所有值,它也应正确排序。例如: [GBP,EUR,NOK,LTU,ZGN] 应该像 ['EUR' ,'NOK','GBP','LTU','ZGN'

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'

我正在使用这个函数进行排序: p>

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?

推荐答案

您可以使用使用map排序和排序顺序的哈希表。如果该值不在哈希表中,则将采用原始顺序。

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

这篇关于通过预定义的规则排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆