Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I make an item in an array come before another after sorting in javascript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'] ```

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading