Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript sort multiple array

Suppose I have this data

Name Mark
John 76
Jack 55
Dani 90

and for the grade

Marks Grade
100-80 A
79 – 60 B
59 – 40 C

suppose i declare the script as

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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

Name Mark Grade
Dani 90 A
John 76 B
Jack 55 C

>Solution :

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 sortByHighestMark (a, b) {
  return b.mark - a.mark;
}

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

const result = data
  .map(([name, mark]) => ({grade: getGrade(mark), name, mark}))
  .sort(sortByHighestMark);

console.log(result);

// and data is unmodified:
console.log(data);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading