Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an object array with custom order?

I have an object array like this:

[
    {keyword: 'E', value: '5'},
    {keyword: 'C', value: '3'},
    {keyword: 'B', value: '2'},
    {keyword: 'D', value: '4'},
    {keyword: 'A', value: '1'},
    {keyword: 'F', value: '6'},
    ...
]

I receive this array from other places and I have no control over the source, also the order that it comes can be completely random.

Now I want to sort the array with ascending order on keyword, with the exception of swapping 2 objects. I know the keyword of the object that I want to swap, let say C, and D in the above array. So the final result I want it to be like this:

[
    {keyword: 'A', value: '1'},
    {keyword: 'B', value: '2'},
    {keyword: 'D', value: '4'},
    {keyword: 'C', value: '3'},
    {keyword: 'E', value: '5'},
    {keyword: 'F', value: '6'},
    ...
]

I have to following code, but I don't know where to put the rest of the code. Please help!

myArray.sort(function(a, b){
     return a.keyword.toLowerCase().localeCompare(b.keyword.toLowerCase());
});
like image 416
MayDay Avatar asked Jul 31 '26 11:07

MayDay


1 Answers

var myArray = [
  {keyword: 'E', value: '5'},
  {keyword: 'C', value: '3'},
  {keyword: 'B', value: '2'},
  {keyword: 'D', value: '4'},
  {keyword: 'A', value: '1'},
  {keyword: 'F', value: '6'}
];

var specialKeywords = [ 'C', 'D' ];

myArray.sort(function(a, b){
  //if the two being compared are 'C' and 'D', treat them special
  if (specialKeywords.indexOf(a.keyword) +1
  && specialKeywords.indexOf(b.keyword) +1) {
    //if a is 'C', it needs to be greater than 'D'
    if (a.keyword = 'C') return 1;
    else return -1;
  } else {
    //one of the elements is not 'C' or 'D', process normally.
    return a.keyword.toLowerCase().localeCompare(b.keyword.toLowerCase());
  }
});

console.log(myArray);
like image 139
Taplar Avatar answered Aug 02 '26 01:08

Taplar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!