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>

0

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.