There are two arrays that I am working with:
Main array:
const items = [
"Лопата 123",
"Empty Forest",
"Forever young",
"My ears",
"Most Important",
"16 Tons",
"Operation Flashpoint",
"Prize A1",
"Нарешті літо",
];
And keys array:
const keys = ["Prize A1", "Forever young", "Most Important"];
The goal is to sort the main array based on the order of the keys array, like this:
const expected = [
"Prize A1",
"Forever young",
"Most Important",
"Лопата 123",
"Empty Forest",
"My ears",
"16 Tons",
"Operation Flashpoint",
"Нарешті літо",
]
I tried to write some code to achieve this, but it's not working correctly:
const expectedOrder = items.sort(function(a, b) {
return keys.indexOf(b) - keys.indexOf(a);
});
const items = [
"Лопата 123",
"Empty Forest",
"Forever young",
"My ears",
"Most Important",
"16 Tons",
"Operation Flashpoint",
"Prize A1",
"Нарешті літо",
];
const keys = ["Prize A1", "Forever young", "Most Important"];
const expectedOrder = items.sort(function(a, b) {
return keys.indexOf(b) - keys.indexOf(a);
});
console.log('expectedOrder', expectedOrder)