Skip to content
Advertisement

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

 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

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement