Home > Blockchain >  I want to sort my words from arr by 2nd letter of each word according to my given pattern
I want to sort my words from arr by 2nd letter of each word according to my given pattern

Time:05-17

/* 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?

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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);

CodePudding user response:

You must reverse your cross loops:

for(let i = 0; i < pattern.length;   i) {
  for(let j = 0; j < arr.length;   j) {
    if(pattern[i] === arr[j][1]) refArr.push(arr[j]);
  }
}
  • Related