Yudi
Yudi

Reputation: 35

Javascript-- sort an array of objects with a specified order of object properties

recently i'm building a small web-app and i have an array of objects such as

[
    {
        id: '3',
        semester: 'summer freshman',
        rating: '10'
    },
    {
        id: '4',
        semester: 'spring freshman', 
        rating: '9.5'
    },
    {
        id: '5',
        semester: 'fall freshman',
        rating: '10'
    }
] 

, how i sort my data in an order such that entries with semester == fall freshman comes first, followed by entries with semester == spring freshman, and finally semester == summer freshman.

In other words, is there a way to sort my array of objects according to the values of the semester property within each object such that it follows this order:

["fall freshman", "spring freshman", "summer freshman", "fall sophomore" ...]

Thank you!!

Upvotes: 1

Views: 175

Answers (2)

shawon191
shawon191

Reputation: 1955

You can use a custom sort method. Keep an array of semesters with your desired order. Then sort your array based on the semester array.

let arr = [
    {id: '3', semester:'summer freshman', rating: '10'}, 
    {id: '4', semester: 'spring freshman', rating: '9.5'}, 
    {id:'5', semester:'fall freshman', rating: '10'}
] 

const semesterList = ["fall freshman", "spring freshman", "summer freshman", "fall sophomore"]

arr.sort((a, b) => semesterList.indexOf(a.semester) - semesterList.indexOf(b.semester))

Upvotes: 5

Nina Scholz
Nina Scholz

Reputation: 386578

You could use an object for sorting order and take a default value for unknown values. With order.default, you could unknown values and take zero or a value smaller than zero for moving to top or a really great value, like Infinity to move the item to the bottom.

For known values, I sugghest to use a value, which is differen from zero, because zero, or an unknown result yields to the default value.

var data = [{ id: '3', semester: 'summer freshman', rating: '10' }, { id: '4', semester: 'spring freshman', rating: '9.5' }, { id:'5', semester: 'fall freshman', rating: '10' }, { id:'99', semester: 'foo freshman', rating: '0' }],
    semesters = ["fall freshman", "spring freshman", "summer freshman", "fall sophomore"],
    order = Object.create(null);
    
    
order.default = Infinity;
semesters.forEach((s, i) => order[s] = i + 1);

data.sort((a, b) => (order[a.semester] || order.default) - (order[b.semester] || order.default));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 0

Related Questions