I am trying to sort an array of objects by a property. I run:
array.sort(function(a, b){
var textA = a.name.toUpperCase();
var textB = b.name.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1: 0
});
To alphabetically sort the array objects first and then I run an array.sort with a custom compare function as below:
array.sort(function(a, b){
if(a.name === b.name){
return -1;
}
return 1;
});
It seems to work with anything object that does not have a duplicate, however, as soon as there are doubles it pushes them all to the end of the array instead of just the extras.
Example:
[
{name: 'Amy'},
{name: 'Amy'},
{name: 'Clark'},
{name: 'Clark'},
{name: 'Dan'},
{name: 'Dave'}
{name: 'Joe'},
{name: 'Joe'}
]
Expected Output:
- Amy
- Clark
- Dan
- Dave
- Joe
- Amy
- Clark
- Joe
Actual Result:
- Dan
- Dave
- Amy
- Amy
- Clark
- Clark
- Joe
- Joe
Sort Code To try and get Expected Result
array.sort(function(a,b){
if(a.name === b.name){return -1}
return 1;
});
I have a feeling the array.sort with a compare function can handle this however I keep playing with return values of 0, -1, 1 and cannot seem to get it to work fully as I would like.
Update
Expected Result Criteria:
If an object has the same name the duplicate should go to the end of the array. For example if there are two 'Amy' one stays at the begining of the array and the duplicate goes to the end. So that all first occurrences of the names wil be at the begining of the array and all the doubles, triples etc will will be reordered each time at the end of the array. So that it could potentially arrange alhpabetical multiple items.
Example:
[
{name: 'Amy'},
{name: 'Amy'},
{name: 'Clark'},
{name: 'Clark'},
{name: 'Clark'},
{name: 'Dan'},
{name: 'Dave'},
{name: 'Joe'},
{name: 'Joe'},
{name: 'Joe'},
]
Expected result:
Amy Clark Dan Dave Joe Amy - Duplicate Clark - Duplicate Joe - Duplicate Clark - Had a third Joe - Had a third
As you can see it orders the first occurrence of all names alphabetically. Then orders the second occurrence alphabetically, and then the third. Until all duplicates are resolved.
After talking in comments it has come to my understanding that it cannot be done in an array.sort function alone. Sort alone with a compare function seems to be great for single or grouping doubles but not for putting doubles at the end of the array.