soraraso42 / learning-journal

0 stars 0 forks source link

2024-03-10 object bracket versus dot notation and sort() customization #28

Open soraraso42 opened 8 months ago

soraraso42 commented 8 months ago

js obj looks like this

{ suit: 'hearts', rank: 'queen', value: 10}

when using .rank , .value to access the value of kv pair, it is okay.

in the orderCards() function, which of the three keys ( or any of possible keys in broader application cases) will be passed is unknown. in other words, when key is a variable, bracket notation must be used. dot notation is undefined here.

In addition, if key(identifier for obj) is like these

Invalid JavaScript Identifier: Starts with a digit. Contains special characters other than underscore (_). Contains spaces or punctuation marks (except for underscores). Examples of invalid identifiers: 123variable, my-variable, my variable, my.variable.

bracket notation must be used.


function getValue(cardsArr){
  return cardsArr.reduce((accumulator,card) => accumulator + card.value,0)
}

function getRanks(cardsArr, rank){
  return cardsArr.filter(card =>  card.rank === rank)
}

function orderCards(cardsArr, prop){
  // a more complext conditional needed for custom sorting func
  // essentially sort() accepts >0, 0, <0
  return cardsArr.sort((a,b) =>{
    // begins conditionals
    // bracket notation must be used to access values 
    // because property name aka key of an object is a varaible, thus not known beforehand
    if(a[prop] > b[prop]){
      return 1
    }
    else if(a[prop] < b[prop]){
      return -1
    }
    else{
      return 0
    }

  })
}