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

196
Views
I want to sort my words from arr by 2nd letter of each word according to my given pattern

/* 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 by 2nd letter of each word according to my given pattern.

['aobcdh','aiabch','obijkl']

#output should be: obijkl aiabch aobcdh */

// I tried this way:

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 = ['aiabch', 'aobcdh', 'obijkl', 'apcsdef', 'leeeeeeeeeeeeeeee']
let refArr = []
for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < pattern.length; j++) {
        if (pattern[j] === arr[i][1]) {
            refArr.push(j)
        }

    }
}
console.log(refArr)

// now what next?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use the sort method and the indexOf function

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 = ['aiabch', 'aobcdh', 'obijkl', 'apcsdef', 'leeeeeeeeeeeeeeee']

const newArr = arr.sort((a, b) => pattern.indexOf(a[1]) - pattern.indexOf(b[1]))
console.log(newArr)

about 4 years ago · Juan Pablo Isaza Report

0

You could generate an object with the order values and sort by this values.

If necessary convert the key to lower case and/or take a default value for sorting unknown letters to front or end.

const
    pattern = 'ebcdifghojklmnupqrstavwxyz',
    array = ['aobcdh', 'aiabch', 'obijkl'],
    order = Object.fromEntries(Array.from(pattern, (l, i) => [l, i + 1]));

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

console.log(array);

about 4 years ago · Juan Pablo Isaza Report

0

Also, you can try this if you does not know Array methods.

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'], arr = ['aiabch', 'aobcdh', 'obijkl', 'apcsdef', 'leeeeeeeeeeeeeeee'], refArr = []

arr.forEach(a => pattern.includes(a[2]) ? refArr.push(a) : null)
console.log(refArr)

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!