user431806
user431806

Reputation: 416

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.

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...

How can i extend the sort to include for the BOOL prop ?

Upvotes: 1

Views: 94

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386710

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

Upvotes: 2

Pointy
Pointy

Reputation: 413826

The first if should be:

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

In the subtraction, boolean true will be treated as 1 and false as 0. That means that the false ones will sort before the true ones, as you say you want.

Upvotes: 1

Related Questions