2

I am trying to sort this array, but it doesn't work for me. I must be doing something stupid, could someone have a look and tell me what is wrong please?

var fruits = [{
  config: {
    priority: 99
  }
}, {
  config: {
    priority: 1
  }
}, {
  config: {
    priority: 10
  }
}];
document.getElementById("demo").innerHTML = JSON.stringify(fruits);

function myFunction() {
  let l = fruits.sort(sort);
  document.getElementById("demo").innerHTML = JSON.stringify(l);
}

function sort(item1, item2) {
  return item1.config.priority < item2.config.priority;
}
<p>Click the button to sort the array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
r3plica
  • 13,017
  • 23
  • 128
  • 290

2 Answers2

1

An integer should be returned from the sort() callback. Subtract the first value from second

var fruits = [{
  config: {
    priority: 99
  }
}, {
  config: {
    priority: 1
  }
}, {
  config: {
    priority: 10
  }
}];
document.getElementById("demo").innerHTML = JSON.stringify(fruits);

function myFunction() {
  let l = fruits.sort(sort);
  document.getElementById("demo").innerHTML = JSON.stringify(l);
}

function sort(item1, item2) {
  return item2.config.priority - item1.config.priority;
}
<p>Click the button to sort the array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

Use - not <

const fruits = [{ config: { priority: 99 } }, { config: { priority: 1 } }, { config: { priority: 10 } }];

document.getElementById("demo").innerHTML = JSON.stringify(fruits);

function myFunction() {
  let l = fruits.sort(sort);
  document.getElementById("demo").innerHTML = JSON.stringify(l);
}

function sort({ config: { priority: p1 }}, { config: { priority: p2} }) {
    return parseInt(p1) - parseInt(p2);
}
<!DOCTYPE html>
<html>
<body>

<p>Click the button to sort the array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

</body>
</html>
Bibberty
  • 4,670
  • 2
  • 8
  • 23