简体   繁体   English

Javascript按其他数组的顺序排序

[英]Javascript sort by order of other array

I have a large dataset I need to sort by a preset order. 我有一个大数据集,需要按预设顺序排序。 It's simple enough to get the array sorted, but the problem is having the values not in the sort order moving to the bottom instead of the top. 它很简单,可以对数组进行排序,但是问题是值的排序顺序不是最底部,而是最底部 Here's my code... 这是我的代码...

var order = ["value1",  "value2", "value3"];
var result = ["value4", "value2","value1","value1", "value3"].sort(function(a,b) {
    var aIndex = order.indexOf(a),
        bIndex = order.indexOf(b);

    if (aIndex > bIndex)
        return 1;
    if (aIndex < bIndex)
        return -1;
    return 0;
});

...and the fiddle . ...和小提琴

I can't figure out how to have a condition that considers something not in the order array to be a lower sort order. 我无法弄清楚如何有一个条件可以将不在order数组中的东西视为较低的排序顺序。 I've tried adding if (aIndex < 0 || bIndex < 0) return -1; 我尝试添加if (aIndex < 0 || bIndex < 0) return -1; before the existing conditions, but this will be potentially incorrect of one of the two is in the sort order. 在现有的条件之前,但是这将是可能不正确的的两个一个排序顺序。

You could try setting aIndex and bIndex to the length of the order array when they are -1, thus pushing them to the end of the array. 您可以尝试将aIndexbIndex设置为order数组的长度(当它们为-1时),从而将它们推到数组的末尾。

Example in this fiddle: http://jsfiddle.net/a3LfP/1/ 该小提琴中的示例: http : //jsfiddle.net/a3LfP/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM