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

351
Views
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;
        });
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

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)

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report

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;
  }, [])
);

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!