I don’t understand the last exercise in this course session : https://www.codecademy.com/paths/front-end-engineer-career-path/tracks/fecp-22-interview-skills/modules/wdcp-22-javascript-algorithm-practice/articles/sorting-with-custom-comparator-functions
When given an input array, we want to sort the array given to an explicit order.
const inputArray = ['a', 'b', 'c', 'd', 'e', 'f', 'n', 'y', 'g'];
const order = ['a', 'n', 'd', 'y'];
The comparator function explicitSort(inputArray, order)
should return:
['a', 'n', 'd', 'y', 'b', 'c', 'e', 'f', 'g']
Here is the function:
const explicitSortWithComparator = (inputArray, order) => {
const explicitComparator = (a, b) => {
let indexA = order.length;
let indexB = order.length;
if (order.includes(a)) {
indexA = order.indexOf(a);
}
if (order.includes(b)) {
indexB = order.indexOf(b);
}
return indexA - indexB;
}
return inputArray.sort(explicitComparator).slice();
}
// Use this array to test your code:
const inputArray = ['a', 'b', 'c', 'd', 'e', 'f', 'n', 'y', 'g']
const order = ['a', 'n', 'd', 'y']
console.log(explicitSortWithComparator(inputArray, order));
module.exports = explicitSortWithComparator;
I don’t understand how this function works and how we can have the right result.
Thanks