Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!