Search code examples
javascriptreactjs

Sort the array as per the rules of card game using a generic method


cards = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen', "Jack", "Queen", "King"] <!- Required Output = [2,3,5,6,8,'Jack','Queen','King'] Question: Sort the array as per the rules of card game using a generic method.


Solution

  • One approach is to use an array with all the cards in the right order as a reference, and rank each card being sorted by its index in the reference array.

    let cards = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen',"Jack","Queen","King"];
    
    // change this to match the rules of card game
    let theRightOrder = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"];
    
    cards.sort((a, b) => theRightOrder.indexOf(a) - theRightOrder.indexOf(b));
    
    console.log(cards);