I'm trying to create a function that does multisorting so that the logic can be called multiple times within the code. However, when called, the results outputted to the console are not sorted - it is exactly the same as data that was passed into the function. I was able to get the code working before it became a separate method (see this post). Why isn't the function returning sorted data?
function multisort(data, sortBy) {
const dataClone = JSON.parse(JSON.stringify(data));
return dataClone.sort((a, b) => {
let result = 0;
sortBy.forEach(o => {
if (result !== 0) return;
const property = o.property;
result = o.direction *
(
a[property] > b[property] ? 1 :
(a[property] < b[property] ? -1 : 0)
);
});
return result;
});
}
const students = [
{
firstName: 'John',
lastName: 'Appletree',
grade: 12
},
{
firstName: 'Mighty',
lastName: 'Peachtree',
grade: 10
},
{
firstName: 'Kim',
lastName: 'Appletree',
grade: 11
},
{
firstName: 'Shooter',
lastName: 'Appletree',
grade: 12
},
{
firstName: 'Peter',
lastName: 'Peachtree',
grade: 12
}
];
const sortBy = [
{
prop:'grade',
direction: -1
},
{
prop:'lastName',
direction: 1
}
];
const sortedStudents = multisort(students, sortBy);
console.log(students);
console.log(sortedStudents);