I have an array of objects. Out of each of these objects onle few of them have a property and I want to sort the array putting those objects at top which have that property.
Ex -
arr= [{key1: "obj1val1", key2 :"obj1val2"},
{key2 :"obj2val2"},
{key1: "obj3val3", key2 :"obj3val3"},
{key2 :"obj4val1"},
{key1: "obj5val1", key2 :"obj5val2"}
]
Sorted by key1
Expected Result - [{key1: "obj1val1", key2 :"obj1val2"},
{key1: "obj3val3", key2 :"obj3val3"},
{key1: "obj5val1", key2 :"obj5val2"},
{key2 :"obj2val2"},
{key2 :"obj4val1"}]
I have tried below approach-
sort : function(arr) {
var copyArr = arr.slice();
var newArr = [];
for(var i=0; i<arr.length; i++){
if(arr[i].key1){
newArr.push(arr[i]);
copyArr.splice(i, 1);
}
}
Array.prototype.push.apply(newArr, copyArr);
return newArr;
}
Not exactly but I see discrepancy from the above approach. For a array bigger length, some of the objects which have key1 are not moved to top.
Can this be done by internal sort method of javascript? If yes, how will the custom function compare ?
Can only support ES5 methods.
splicewhile you are iterating.sort.spliceout one element.var withProp = [], withoutProp = []; … if ("key1" in arr[i]) withProp.push(arr[i]); else withoutProp.push(arr[i]); …. Don't copy anything beforehand or try to splice from it during a loop.