Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
I just want to sort my words from array alphabetically by 1st letter and then by 2nd letter according to my given pattern which matched by 1st letter

♦ pattern: e,b,c,d,i,f,g,h,o,j,k,l,m,n,u,p,q,r,s,t,a,v,w,x,y,z

I want to sort my words from arr alphabetically by 1st letter and then by 2nd letter of a similar word matched by 1st letter according to my given pattern.

['aobcdh', 'aibcdh', 'aabcdh', 'aacbdh', 'cfghjd', 'cighjd']

♦ output should be:

['aibcdh', 'aobcdh', 'aabcdh', 'aacbdh', 'cighjd', 'cfghjd' ]

♦ or: aibcdh aobcdh aabcdh aacbdh cighjd cfghjd

My Code here:

    let pattern = ['e', 'b', 'c', 'd', 'i', 'f', 'g', 'h', 'o', 'j', 'k', 'l', 'm', 'n', 'u', 'p', 'q', 'r', 's', 't', 'a', 'v', 'w', 'x', 'y', 'z']
let arr = ['aobcdh', 'aibcdh', 'aabcdh', 'aacbdh', 'cfghjd', 'cighjd']
let arrSorted = arr.sort() //Natural sorting
console.log(arrSorted)

// output in array
const newArr = arrSorted.sort((a, b) => pattern.indexOf(a[1]) - pattern.indexOf(b[1]))
console.log(newArr) //Sorted by its 2nd character with given pattern

// single output without array
for (let i = 0; i < pattern.length; i++) {
    for (let j = 0; j < arrSorted.length; j++) {
        if (pattern[i] === arrSorted[j][1]) {
            console.log(arrSorted[j]) //Sorted by its 2nd character with given pattern
        }
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could sort the first by string and the second by custom value.

const
    pattern = 'ebcdifghojklmnupqrstavwxyz',
    array = ['aobcdh', 'aibcdh', 'aabcdh', 'aacbdh', 'cfghjd', 'cighjd'],
    order = Object.fromEntries(Array.from(pattern, (l, i) => [l, i + 1]));

array.sort((a, b) =>
    a[0].localeCompare(b[0]) ||
    order[a[1]] - order[b[1]]
);

console.log(array);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda