I have an array of strings which can be seen as a template / reference:
// Template
let template = ['A', 'B', 'C'];
I also have an array of objects containing some of the array's strings:
// Source (to be sorted)
let source = [
{ items: ['B', 'D', 'E'] },
{ items: ['E', 'L', 'Y'] },
{ items: ['G', 'B', 'A'] },
{ items: ['C', 'B', 'A'] }
];
I now need to find a way to sort the items in the source array by matching to the template array (from best to worst). The order of the strings in the items is irrelevant.
Based on my example above, the result after sorting would look like this:
// Result after sorting
let sorted = [
{ items: ['C', 'B', 'A'] }, // 3 matches (A, B, C)
{ items: ['G', 'B', 'A'] }, // 2 matches (A, B)
{ items: ['B', 'D', 'E'] }, // 1 match (B)
{ items: ['E', 'L', 'Y'] } // no match
];
With the JavaScript method .sort() and .localCompare() I can sort an array based on strings but I couldn't find a way to sort by a given array 'template'.
I would be more than happy if somebody knows a way how to do that? Thank you in advance!