Home > Software engineering >  Sorting Characters Where The Characters are Valued Differently In My Project Context
Sorting Characters Where The Characters are Valued Differently In My Project Context

Time:05-20

I want to sort an array of characters consisting of letters F, S, T. There may be duplicates of each character.

Example input Arrays:

['F', 'F', 'S', 'T', 'T']
['F', 'S']
['T', 'S', 'S', 'F']

In the context of my project, T = 0, F = 1, S = 2, So when an array is sorted, if T is in the array, it should be the first index. F should be the second index, and S should be the third index. Is there a way I can make this happen?

CodePudding user response:

Define a way to score, then use that in a custom Array.prototype.sort function.

Array.prototype.slice(0) is used since .sort mutates the original array.

const score = {
  "T": 0,
  "F": 1,
  "S": 2,
}

const tests = [
  ['F', 'F', 'S', 'T', 'T'],
  ['F', 'S'],
  ['T', 'S', 'S', 'F']
];

for (const test of tests) {
  const sorted = test.slice(0).sort((a, b) => score[a] - score[b]);
  console.log(sorted);
}

CodePudding user response:

Create a simple array of the letters in the order you want. Accept an unlimited amount of parameters with the ...rest operator:

const key = ['T', 'F', 'S'];
const sortByKeyIndex = (ki, ...arr) => {// ([key], ...[A], [B], [C])

Merge the arrays from the ...rest operator -- which makes an array of arrays and then run .map()

[...arr].map(a => //...[[A], [B], [C]]

Next, .sort() each sub-array comparing each letter to the index of ki (key) with .findIndex():

a.sort((x, y) => ki.findIndex(k => x === k) - ki.findIndex(k => y === k)));

const key = ['T', 'F', 'S'];
let A = ['F', 'F', 'S', 'T', 'T'],
  B = ['F', 'S'],
  C = ['T', 'S', 'S', 'F'];

const sortByKeyIndex = (ki, ...arr) => {
  return [...arr].map(a => a.sort((x, y) => ki.findIndex(k => x === k) - ki.findIndex(k => y === k)));
}

console.log(sortByKeyIndex(key, A, B, C));

  • Related