• Empleos
  • Sobre nosotros
  • Empleos
    • Inicio
    • Empleos
    • Cursos y retos
  • Empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

330
Vistas
How to sort strings by hit count?

I have an string array

const arr = ['ACST', 'CST', 'CCST'];;

And i have const word = 'CS'; How to sort array to be

const newArr = ['CST', 'CCST', 'ACST'];

I tried something like this, but it looks bad, and doesn't work correct; Output CCST -> CST ... , should be CST -> CCST

arr.sort((a, b) => {
            let A = 0;
            let B = 0;
            for (let i = 0; i < word.length; i++) {
                if (a.charAt(i) === word.charAt(i)) {
                    A++;
                }
                if (b.charAt(i) === word.charAt(i)) {
                    B++;
                }
            }
            return A + B;
        });
over 3 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You almost got it! You just need to return -1 or 1 to tell the sort algorithm which value to pick.

const arr = ['ACST', 'CST', 'CCST'];;

const newArr = ['CST', 'CCST', 'ACST'];

const word = 'CS'

arr.sort((a, b) => {
    let A = 0;
    let B = 0;
    for (let i = 0; i < word.length; i++) {
        if (a.charAt(i) === word.charAt(i)) {
            ++A;
        }
        if (b.charAt(i) === word.charAt(i)) {
            ++B;
        }
    }
    return A > B ? -1 : 1;
});

console.log(arr)

over 3 years ago · Juan Pablo Isaza Denunciar

0

If you want to sort by the number of matching characters at corresponding indexes, you should subtract the count for the two strings in the comparator function (i.e. A - B for ascending order and B - A for descending order).

const arr = ['ACST', 'CST', 'CCST'];
const word = 'CS';
arr.sort((a, b) => {
  let A = 0;
  let B = 0;
  for (let i = 0; i < word.length; i++) {
    if (a.charAt(i) === word.charAt(i))
      A++;
    if (b.charAt(i) === word.charAt(i))
      B++;
  }
  return B - A;
});
console.log(arr);

over 3 years ago · Juan Pablo Isaza Denunciar

0

If i got the point correctly:

const arr = ['CRST','CSX', 'CKST', 'CST', 'CCST'];

var lastIndex = 0;
console.log(
  arr.reduce((r, i, index) => {
    if (i.match(/^CS/) || i.match(/^CS./)) {
      r.unshift(i);
      lastIndex = lastIndex+1;
    } else if (i.match(/CS./)) {
      r.splice(lastIndex, 0, i);
    } else r.push(i);

    return r;
  }, [])
);

over 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda