Muhammad Zarith
Muhammad Zarith

Reputation: 39

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

Upvotes: 0

Views: 64

Answers (2)

jsejcksn
jsejcksn

Reputation: 33901

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);

Upvotes: 2

Persyl
Persyl

Reputation: 383

If you mean that you expect output like:

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?

Upvotes: 0

Related Questions