-2

How to sort this data by score and display it in a <table>?

[
  { "name": "xyz", "email": "xyz@gmail.com", "score": 0 },
  { "name": "abc", "email": "abc@gmail.com", "score": 1 }
]
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43

3 Answers3

0
data = [
  { "name": "xyz", "email": "xyz@gmail.com", "score": 0 },
  { "name": "abc", "email": "abc@gmail.com", "score": 1 }
]

data.sort(function(a, b){
   return a.score - b.score;
})
0

You may try to do it like this. It will sort by the "score".

list = [
  { "name": "xyz", "email": "xyz@gmail.com", "score": 3 },
  { "name": "abc", "email": "abc@gmail.com", "score": 2 },
  { "name": "ert", "email": "ert@gmail.com", "score": 0 },
  { "name": "zsr", "email": "zsr@gmail.com", "score": 1 }
]

list.sort((a, b) => (a.score > b.score) ? 1 : -1)

console.log(list)
Mohsen Alyafei
  • 4,765
  • 3
  • 30
  • 42
0

const data = [
  { "name": "xyz", "email": "xyz@gmail.com", "score": 0 },
  { "name": "abc", "email": "abc@gmail.com", "score": 1 }
].sort((a, b) => b.score - a.score);
const table = document.createElement('table');
document.body.append(table);
const tr = document.createElement('tr');
table.append(tr);
for (const key of Object.keys(data[0])) {
  const th = document.createElement('th');
  th.textContent = key;
  tr.append(th);
}
data.forEach(datum => {
  const trB = document.createElement('tr');
  table.append(trB);
  Object.values(datum).forEach(value => {
    const td = document.createElement('td');
    td.textContent = value;
    trB.append(td);
  });
});
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43