1

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!!

1
  • Can you please share what you have tried? Commented Aug 30, 2017 at 6:33

2 Answers 2

5

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))
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what im lookign for. Thank you so much!!
0

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; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.