The function must receive three parameters: array, order, and key. The key must determine the order of the array, as in the example:
let arr = [
{id: 5, name: 'Hugo'},
{id: 2, name: 'Julian'},
{id: 3, name: 'Anne'},
{id: 1, name: 'April'},
{id: 4, name: 'John'}
];
let order = [1, 2, 3, 4, 5];
mapOrder(arr, order, 'id');
must return:
0: {id: 1, name: "April"}
1: {id: 2, name: "Julian"}
2: {id: 3, name: "Anne"}
3: {id: 4, name: "John"}
4: {id: 5, name: "Hugo"}
function mapOrder(array, order, key) {
if (typeof array !== 'object' || typeof order !== 'object' || typeof key !== 'string') return [];
array.sort((a, b) => {
let A = a[key], B = b[key];
if (order.indexOf(A) > order.indexOf(B)) {
return 1;
} else return -1;
});
return array;
}
const chai = require("chai");
const assert = chai.assert;
const Test = require("@codewars/test-compat");
describe("Solution", function() {
it("Must return the ordered array of objects", function() {
const arr = [
{id: 5, name: 'Hugo'},
{id: 2, name: 'Julian'},
{id: 3, name: 'Anne'},
{id: 1, name: 'April'},
{id: 4, name: 'John'}
];
const orderedArray = [
{id: 1, name: "April"},
{id: 2, name: "Julian"},
{id: 3, name: "Anne"},
{id: 4, name: "John"},
{id: 5, name: "Hugo"}
];
assert.strictEqual(JSON.stringify(mapOrder(arr, [
1, 2, 3, 4, 5
], 'id')), JSON.stringify(orderedArray));
});
it("Must return an empty array in case of any wrong parameter", function() {
assert.strictEqual(String(mapOrder('randomString', 'foo', 3)), '');
});
});