Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  42] [ 3]  / answers: 1 / hits: 10946  / 10 Years ago, fri, april 25, 2014, 12:00:00

I have an array of objects that I am trying to sort but it does not seem to be working. Some objects in the array have a orderNum property which I am targeting to sort. But not all objects have this property.



I want the objects with the orderNum property to be sorted to the top positions in the array.



Here is a fiddle to what i have tried: http://jsfiddle.net/7D8sN/



Here is my javascript:



var data = {
attributes: [
{
value: 123-456-7890,
name: phone
},
{
value: [email protected],
name: email
},
{
value: Gotham,
name: city,
orderNum: 1
},
{
value: 12,
name: ID
},
{
value: Batman,
name: Super Hero,
orderNum: 2
}
]
};

data.attributes.sort( function (a, b) {
if (a.orderNum < b.orderNum) {
return -1;
}
if (a.orderNum > b.orderNum) {
return 1;
}

return 0;
});

console.log(data);

More From » arrays

 Answers
2

Check if the property exists in your sort function.



data.attributes.sort( function (a, b) {
if ((typeof b.orderNum === 'undefined' && typeof a.orderNum !== 'undefined') || a.orderNum < b.orderNum) {
return -1;
}
if ((typeof a.orderNum === 'undefined' && typeof b.orderNum !== 'undefined') || a.orderNum > b.orderNum) {
return 1;
}

return 0;
});

[#45748] Thursday, April 24, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chazw

Total Points: 127
Total Questions: 129
Total Answers: 92

Location: Sao Tome and Principe
Member since Wed, Dec 21, 2022
1 Year ago
;