0

I am working on a function that will sort my list under midterm score grade ascendingly. So I tried the ff codes:

if(score === 'Midterm Score'){
         _.each(students, function(elem, index, list){
           _.sortBy(students, function(elem){
              console.log(elem.midterm_score);
           });
          });
       }

So using the elem.midterm_score it did not sort my list via midterm score as can be seen here.

enter image description here

I expect it to be 90, 80, 70 and so on something like that. Any idea what am I missing? Please help!

2 Answers 2

1

You are using the sortBy method in the wrong way. Check it in the docs

// First of all we need students
var students = [
    {name: 'a', midterm_score: 60}, 
    {name: 'b', midterm_score: 70}, 
    {name: 'c', midterm_score: 40}
];

// Sort by midterm score and assign to students variable
students = _.sortBy(students, 'midterm_score');

// print array in each loop
_.each(students, function(el) {
    console.log(el);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I think this one works. I should have switch the places of the each and just put the sorted items in a variable.
0

According to the docs:

Returns a (stably) sorted copy of list, ranked in ascending order by the results of running each value through iteratee. iteratee may also be the string name of the property to sort by (eg. length).

It may be that you are overcomplicating things. To sort the list based on the value of a property such as midterm_score, simply pass it as the second argument, as such:

sortBy(students, 'midterm_score');

Using a function as the iteree is for transformations on your data, which does not seem necessary here. You are expected in such a function to return the transformed result, using the return command explicitly (according to the docs).

Comments

Your Answer

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