javascript - TypeError: The comparison function must be either a function or undefined - Stack Overflow

Write a function named "sort_by_average" that takes a listarray of key-value stores as a par

Write a function named "sort_by_average" that takes a list/array of key-value stores as a parameter where each key-value store has keys "ratings", "budget", and "box_office" where budget and box_office are integers and ratings is a list of integers. Sort the input based on the average of the values in "ratings"

function sort_by_average(lista){
    for(var i of lista){
        lista.sort(i.ratings.reduce/i.ratings.length);
    }
    return lista;
}

I am getting TypeError: The parison function must be either a function or undefined. How can I fix this?

Write a function named "sort_by_average" that takes a list/array of key-value stores as a parameter where each key-value store has keys "ratings", "budget", and "box_office" where budget and box_office are integers and ratings is a list of integers. Sort the input based on the average of the values in "ratings"

function sort_by_average(lista){
    for(var i of lista){
        lista.sort(i.ratings.reduce/i.ratings.length);
    }
    return lista;
}

I am getting TypeError: The parison function must be either a function or undefined. How can I fix this?

Share Improve this question asked Nov 14, 2018 at 15:45 user10649535user10649535 1
  • Hello mate, the Array.protoytype.sort() requires a function as parameter or undefined, that's why you encounter TypeError. You also don't have to loop through the list to sort it, you can take a look at the example provided in the link above. – ptdien Commented Nov 14, 2018 at 15:54
Add a ment  | 

1 Answer 1

Reset to default 2

If pareFunction is supplied, all non-undefined array elements are sorted according to the return value of the pare function (all undefined elements are sorted to the end of the array, with no call to pareFunction).

So you have to create a function like this and pass it to sort():

function pare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

More information

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745040282a4607769.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信