Exploring a practical demonstration of sorting an array of objects based on multiple properties, the code implementation involves a while
loop (refer to students1
in the snippet below). I attempted to streamline this process by using .forEach
, but encountered a discrepancy in the output compared to the original while
loop. What might have caused this divergence when refactoring with .forEach
?
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 students1 = JSON.parse(JSON.stringify(students));
const students2 = JSON.parse(JSON.stringify(students));
students1.sort((a, b) => {
let i = 0, result = 0;
while (i < sortBy.length && result === 0) {
const prop = sortBy[i].prop;
const direction = sortBy[i].direction;
result = direction *
(
a[prop].toString() < b[prop].toString() ? -1 :
(a[prop].toString() > b[prop].toString() ? 1 : 0)
);
i++;
}
return result;
});
students2.sort((a, b) => {
let result = 0;
sortBy.forEach(o => {
result = o.direction *
(
a[o.prop].toString() < b[o.prop].toString() ? -1 :
(a[o.prop].toString() > b[o.prop].toString() ? 1 : 0)
);
});
return result;
});
console.log(students);
console.log('one', students1);
console.log('two', students2);