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());
});
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With