Skip to content
Advertisement

reorder an array elements based on first phrase in pattern of elements

I have a pairs array consist of an specific pattern (first phrase = second phrase). I want to reorder the pairs array based on first phrase (I give the first phrase as phrase variable)

This is not an easy task for me because I can’t find a proper solution to reorder the pairs array elements when it’s consists of two separate phrases…

const pairs = ["they're = they are", "Your Majesty = your highness"];

const phrase = "your majesty"; // this is always lowercase

function reorderPairs() {
 // I want to bring "Your Majesty = your highness" to the first position
 
 // expected result would be: ["Your Majesty = your highness", "they're = they are"];


}

Advertisement

Answer

You could filter pairs that matchs the phrase and then concat with the rest

const pairs = ["they're = they are", "Your Majesty = your highness"]
const phrase = "your majesty"

function reorderPairs() {
  const pairsMatchPhrase = pairs.filter(
    (pair) => pair.split(" = ")[0].toLowerCase() === phrase
  )
  const pairsNotMatchPhrase = pairs.filter(
    (pair) => pair.split(" = ")[0].toLowerCase() !== phrase
  )
  return pairsMatchPhrase.concat(pairsNotMatchPhrase)
}

console.log(reorderPairs())
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement