Order array by predefined rules

后端 未结 4 1567
猫巷女王i
猫巷女王i 2020-12-22 06:29

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

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-22 06:44

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

提交回复
热议问题