kayza kayza - 5 months ago 16
Javascript Question

Sorting an array with more than two states

I try to sorting an array but the output is not this, what I want.

I have an array like this:

var myArray = [
{
...
"foo": false,
"bar": true,
...
},
{
...
"foo": true,
"bar": false,
...
},
{
...
"foo": true,
"bar": false,
...
},
{
...
"foo": false,
"bar": false,
...
},
...
];


and I want sort this array this way

myArray.sort(function(a,b) {
var foo = a.foo;
var bar = b.bar;

if(foo === false && bar === true) {
// this should sort on top
return -1;
}

if(foo === false && bar === false) {
// this should sort as second
return 0;
}

if(foo === true && bar === true) {
// this should sort as third
return 0;
}

if(foo === true && bar === false) {
// this should sort as last
return 1;
}
});


I think I have a logical problem with
sort
function.

What I want as output is I comment it in the if comments for you

Answer

You can add a weightage property to the array objects based on the existing conditions. Like

var tempArr = myArray.map(function(obj) {
    var foo = obj.foo;
    var bar = obj.bar;

    if (foo === false && bar === true) {
        // this should sort on top
        obj.weightage = 1;
    }

    if (foo === false && bar === false) {
        // this should sort as second
        obj.weightage = 2;
    }

    if (foo === true && bar === true) {
        // this should sort as third
        obj.weightage = 3;
    }

    if (foo === true && bar === false) {
        // this should sort as last
        obj.weightage = 4;
    }

    return obj;
});

and then use the sort function on array

tempArr = tempArr.sort(function(a, b) {
    return a.weightage - b.weightage;
});