Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

♦ 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
        }
    }
}

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading