I was given a array to sort but after sorting the array a particular element should come before another.
var array = ['Jack', 'Queen', 'King', 1,3, 2, 4, 5, 6, 7];
the output should be // 1,2,3,4,5,6,7,Jack,Queen,King
In which Queen would come before King My solution:
var array = ['Jack', 'Queen', 'King', 1,3, 2, 4, 5, 6, 7];
array.sort()
console.log(array); ```
But my output is:
```[1, 2, 3, 4, 5, 6, 7, 'Jack', 'King', 'Queen'] ```
CodePudding user response:
Map Jack
, Queen
and King
to numbers, sort the integer array and then reverse map numbers for Jack
, Queen
and King
.
var array = ['Jack', 'Queen', 'King', 1, 3, 2, 4, 5, 6, 7];
const ans = array
.map(x => {
if (x === 'Jack') return 10;
else if (x === 'Queen') return 11;
else if (x === 'King') return 12;
return x;
})
.sort((a, b) => a - b)
.map(x => {
if (x === 10) return 'Jack';
else if (x === 11) return 'Queen';
else if (x === 12) return 'King';
return x;
});
console.log(ans);
CodePudding user response:
The letter Q is after letter K in the alphabet A B C D E F G H I J K L M N O P Q R S T U V X Y Z that's how it goes So sorting works properly if you want it to sort other way you should create custom sort.
Look into compare section here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort and also I would suggest going with different approach of having the map array with the "cards" because I think thats what you wanna sort ordered correctly and just compare indices from that array or key value map. Example with custom compare function and card values map.
const cardValueMap = {
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 7,
8: 8,
9: 9,
10: 10,
Jack: 11,
Queen: 12,
King: 13,
Ace: 14,
}
const array = ['Jack', 'Queen', 'King', 3, 2, 4, 5, 6, 7]
const compareCards = (a, b) => {
if (cardValueMap[a] < cardValueMap[b]) {
return -1
}
if (cardValueMap[a] > cardValueMap[b]) {
return 1
}
return 0
}
array.sort(compareCards)
console.log(array)
Could be upgraded by checking typeof a
/ typeof b
to not have to include numbers in map.
Note that I also removed "1" from your array since there is no card with number 1.