How do I sort an array as close as possible to a target array as possible.
For example:
The array can only contain a maximum of 4 elements:
['javascript', 'html', 'css', 'result'];
But in cases where it isn't, the sorting should be as follows:
['css', 'result', 'html']; sorted to ['html', 'css', 'result'];
['result', 'css', 'javascript']; sorted to ['javascript', 'css', 'result'];
The criteria is to get it as close to ['javascript', 'html', 'css', 'result']; as possible, and where a particular element does not exist, skip it.
My current code seems to do it incorrectly, I've included it below:
function setFiddleTabsArray(updatedFiddleTabs) {
if (updatedFiddleTabs.length === 4) {
updatedFiddleTabs = ['javascript', 'html', 'css', 'result'];
} else {
const correctFiddleTabsOrder = ['javascript', 'html', 'css', 'result'];
const fiddleTabsSorter = (a, b) => {
if (correctFiddleTabsOrder.includes(a)) {
return -1;
}
if (correctFiddleTabsOrder.includes(b)) {
return 1;
}
return 0;
};
updatedFiddleTabs.sort(fiddleTabsSorter);
return updatedFiddleTabs;
}
return updatedFiddleTabs;
}
const test1 = setFiddleTabsArray(['css', 'html', 'result']);
console.log(test1);
How do I fix it?
['javascript', 'html', 'css', 'result'];as possible, and where a particular element does not exist, skip it.