简体   繁体   English

自定义array.sort函数,包含多个条件。 布尔

[英]custom array.sort function with several criteria incl. boolean

I have an array of objects that i would like to order by several properties. 我有一个对象数组,我想通过几个属性来订购。

Im going to showcase a single element of the array 我将展示数组的单个元素

var ele = {
    id: INT, various,
    priority: INT 1 - 10,
    shooterid: INT various,
    targetid: INT various,
    flight: BOOL
}

i would like to order the array according to some criteria and i can do the sort by priority, shooter and target by using 我想根据一些标准订购阵列,我可以通过使用优先级,射手和目标进行排序

if (a.priority != b-priority){
  return a-priority - b-priority;
else if a.shooterid != b.shooterid){
  return a.shooterid - b. shooterid
}
else return a.targetid - b.targetid

However, i also want to sort by flight and i would like to all elements with flight = true to be sorted LAST in addition to the above sort. 但是,我也希望按航班排序, 除了上述排序之外 ,我还希望所有具有flight = true元素最后排序。

I tried if (a.flight){return -1/0/1} a the very top of the above if/self (adding else to the formerly if) but it didnt work... 我试过if (a.flight){return -1/0/1} a上面的最上面的if / self(除了以前的if之外),但它没有用...

How can i extend the sort to include for the BOOL prop ? 我如何扩展排序以包括BOOL道具?

You could combine all sort criteria with logical or || 您可以将所有排序条件与逻辑或||组合在一起 , even the boolean values. ,甚至是布尔值。

 var data = [{ id: 0, flight: true, priority: 1, shooterid: 2, targetid: 1 }, { id: 1, flight: true, priority: 2, shooterid: 2, targetid: 3 }, { id: 2, flight: false, priority: 1, shooterid: 1, targetid: 2 }, { id: 3, flight: false, priority: 2, shooterid: 1, targetid: 1 }, { id: 4, flight: true, priority: 1, shooterid: 1, targetid: 2 }]; data.sort(function (a, b) { return ( a.flight - b.flight || a.priority - b.priority || a.shooterid - b.shooterid || a.targetid - b.targetid ); }); console.log(data); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The first if should be: 第一if应该是:

if (a.flight != b.flight)
  return a.flight - b.flight;

In the subtraction, boolean true will be treated as 1 and false as 0 . 在减法中,布尔值true将被视为1false将被视为0 That means that the false ones will sort before the true ones, as you say you want. 这意味着false那些将在true那些之前排序,正如你所说的那样。

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

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