-3

I want to arrange my data.

If the score is 30 the time will be in ascending order. Else I need to arrange the score in descending order. The final Object will be like this:

[{
  "Name": "Mac",
  "Score": "30",
  "Time": "104"
}, {
  "Name": "Tomas",
  "Score": "30",
  "Time": "105"
}, {
  "Name": "Alex",
  "Score": "28",
  "Time": "120"
}, {
  "Name": "Ank",
  "Score": "26",
  "Time": "110"
}]

const text = [{
  "Name": "Tomas",
  "Score": "30",
  "Time": "105"
}, {
  "Name": "Ank",
  "Score": "26",
  "Time": "110"
}, {
  "Name": "Alex",
  "Score": "28",
  "Time": "120"
}, {
  "Name": "Mac",
  "Score": "30",
  "Time": "104"
}]

text.sort(function(a, b) {
  return b.Score - a.Score
});

displayCars();

function displayCars() {
  document.getElementById("demo").innerHTML =
    text[0].Time + " - " + text[0].Name + "<br>" +
    text[1].Time + " - " + text[1].Name + "<br>" +
    text[2].Time + " - " + text[2].Name + "<br>" +
    text[3].Time + " - " + text[3].Name;
}
<p id="demo"></p>

I have tried this code. It sort the data but not as I expected.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
ayan
  • 5
  • 1
  • 3
  • Score is a string. You’ll have to use parseInt – Daniel A. White Mar 29 '23 at 12:13
  • 1
    So are you trying to sort by `score`, but if the value is the same then sort by `time`? – Nick Parsons Mar 29 '23 at 12:13
  • 2
    @DanielA.White subtraction between numeric strings works, so while it's odd, OP doesn't need to use `parseInt` – Nick Parsons Mar 29 '23 at 12:14
  • "*If the score is 30 the time will be in ascending order.*" is quite unclear. Sorting is always about comparing to items. What if for both items the score is 30, what if only for one of them the score is 30? How should the two items be ordered in these cases? – derpirscher Mar 29 '23 at 12:18
  • Also: `const displayCars = () => document.getElementById("demo").innerHTML = text .map(({Time,Name}) => \`${Time} - ${Name}\`).join('
    ');`
    – mplungjan Mar 29 '23 at 12:39

1 Answers1

0

const data = '[{"Name":"Tomas","Score":"30","Time":"105" },{"Name":"Ank","Score":"26","Time":"110" },{"Name":"Alex","Score":"28","Time":"120" },{"Name":"Mac","Score":"30","Time":"104" }   ]';
let text = JSON.parse(data);

text.sort((a, b) => {
  // try to sort by score, descending
  const diff = parseInt(b.Score) - parseInt(a.Score);
  // if the score is tied, then sort by time, ascending
  if (diff === 0) return parseInt(a.Time) - parseInt(b.Time);
  // otherwise, return order based on just the scores
  return diff;
});

displayCars();

function displayCars() {
  document.getElementById("demo").innerHTML =
  text[0].Time + " - " + text[0].Name + "<br>" +
  text[1].Time + " - " + text[1].Name + "<br>" +
  text[2].Time + " - " + text[2].Name + "<br>" +
  text[3].Time + " - " + text[3].Name;
}
<p id="demo"></p>
Dennis Kats
  • 2,085
  • 1
  • 7
  • 16