简体   繁体   English

JavaScript 排序多个数组

[英]JavaScript sort multiple array

Suppose I have this data假设我有这些数据

Name姓名 Mark标记
John约翰 76 76
Jack杰克 55 55
Dani丹妮 90 90

and for the grade和年级

Marks分数 Grade年级
100-80 100-80 A一个
79 - 60 79 - 60 B
59 - 40 59 - 40 C C

suppose i declare the script as假设我将脚本声明为

 let data = [
  [John, 76],
  [Jack, 55],
  [Dani, 90]
];

The program should assign the grade with the corresponding mark, how do I sort the grade since we know we cant change the index for mark as usual because each mark assign to different student?程序应该用相应的标记分配成绩,我如何对成绩进行排序,因为我们知道我们不能像往常一样更改标记的索引,因为每个标记分配给不同的学生? The output should display all data in descending order as output 应按降序显示所有数据

Name姓名 Mark标记 Grade年级
Dani丹妮 90 90 A一个
John约翰 76 76 B
Jack杰克 55 55 C C

I would break it up into different functions so that you can handle each task separately.我会将其分解为不同的功能,以便您可以分别处理每个任务。 Then you can combine them to produce your desired result, like this:然后您可以将它们组合起来以产生您想要的结果,如下所示:

 const grades = [ ['A', 80], ['B', 60], ['C', 40], ]; function getGrade (mark) { for (const [grade, minMark] of grades) { if (mark < minMark) continue; return grade; } return 'F'; // use minimum grade as default if mark is too low } function mapToObject ([name, mark]) { return {grade: getGrade(mark), name, mark}; } function sortByHighestMark (a, b) { return b.mark - a.mark; } const data = [ ['John', 76], ['Jack', 55], ['Dani', 90] ]; const result = data.map(mapToObject).sort(sortByHighestMark); console.log(result); // and data is unmodified: console.log(data);

If you mean that you expect output like:如果您的意思是您期望 output 像:

Dani - A
John - B
Jack - C

Then I would do something like:然后我会做类似的事情:

A method:一个方法:

getGrade(points => {
  if(points >= 80 && points <= 100) return 'A'
  if(points >= 60 && points < 80) return 'B'
  return 'C'
})

Then have data as:然后将数据设为:

    const data = [
                 {name: 'John', value: 76},
                 {name: 'Jack', value: 55},
                 {name: 'Dani', value: 90},
                 ]

Then just do:然后做:

data.sort((student1, student2) => {
 if(getGrade(student1.value) === student2.value) return 0
 return (getGrade(student1.value) > getGrade(student2.value))? 1 : -1
})

I hope I understood you correct?我希望我理解你正确吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM