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