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

Time:03-31

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.

CodePudding user response:

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);

CodePudding user response:

This solution avoids mutating the original array and instead provides a shallow-copy of the cards in the sorted-order. It allows being called with parameters to indicate whether:

a. Ace is low (default) or high

b. Duplicates need to be removed (default) or retained

c. The sorted array needs to be ascending (default) or descending

const handleDupes = (fl, ar) => (fl ? [...new Set(ar)] : ar);

const sortCards = (arr, aceHigh = false, removeDupes = false, descending = false) => {
  const sorted = [...Array(9)].map(
    (x, i) => (i   2)
  ).concat(
    "Jack, Queen, King".split(', ')
  );
  if (aceHigh) sorted.push("Ace");
  else sorted.splice(0, 1, "Ace");
  return handleDupes(
    removeDupes, 
    [...arr]
    .sort(
      (a, b) => (
        sorted.indexOf(a) > sorted.indexOf(b)
        ? descending ? -1 : 1
        : descending ? 1 : -1
      )
    )
  );
};

const unsorted = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen', "Jack", "Queen", "King"];

console.log(sortCards(unsorted, true, true));

CodePudding user response:

cards = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen',"Jack","Queen","King"]

numbers = []
jacks = []
kings = []
queens = []

cards.map(i=>{
  if(typeof(i)==="number"){
    numbers.push(i)
    numbers.sort()
  } else if (typeof(i)==="string" && i ==="Jack"){
    jacks.push(i)
  } else if (typeof(i)==="string" && i ==="King"){
    kings.push(i)
  } else {
    queens.push(i)
  }
})

var words = [...numbers,...jacks,...queens,...kings]
  
console.log(words)
  • Related