Sorting array by order to another array
I have two arrays:
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"];
I want to sort the first array in the order of the key array, for example:
const expected = [
"Prize A1",
"Forever young",
"Most Important",
"Лопата 123",
"Empty Forest",
"My ears",
"16 Tons",
"Operation Flashpoint",
"Нарешті літо",
]
I writed some code, but it doesn’t work as it should:
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)