Md. Nazmul Hossain Bilash Md. Nazmul Hossain Bilash - 2 months ago 10
Javascript Question

sorting for array object needed in JavaScript using default .sort()

I have an array :

var array = [
{ID : 1,
Name : one,
data : {more info here}
},
{ID : 2,
Name : two
},
{ID : 3,
Name : three,
data : {more info here}
},
{ID : 4,
Name : four
},
{ID : 5,
Name : five,
data : {more info here}
},]


Need to sort these array, where data is present will be top, then other.
Final sort result will be -

[{ID:1,name: one,data: {}},
{ID:3,name: three,data: {}},
{ID:5,name: five,data: {}},
{ID:2,name: two},
{ID:4,name: four}]

Answer

You could use the delta of the boolen values of the properties.

var array = [{ ID: 1, Name: 'one', data: {} }, { ID: 2, Name: 'two' }, { ID: 3, Name: 'three', data: {} }, { ID: 4, Name: 'four' }, { ID: 5, Name: 'five', data: {} }];

array.sort(function (a, b) {
    return !a.data - !b.data;
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Another version with stress on the key could be the check for existence.

var array = [{ ID: 1, Name: 'one', data: {} }, { ID: 2, Name: 'two' }, { ID: 3, Name: 'three', data: {} }, { ID: 4, Name: 'four' }, { ID: 5, Name: 'five', data: {} }];

array.sort(function (a, b) {
    return ('data' in b) - ('data' in a);
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }