0
const arr = [2133, 435, 34, 234, 655, 345, 112, 4, 432, 6654, 1001];

const output = {
    asc_1: [],
    asc_2: [],
    desc_1: [],
    desc_2: []
};

output.asc_1 = arr.sort((a, b) => (a > b ? 1 : 0)); // Sort values low to high
output.desc_1 = arr.sort((a, b) => (a < b ? 1 : 0)); // Sort values high to low
output.asc_2 = arr.sort((a, b) => a - b); // Sort values low to high
output.desc_2 = arr.sort((a, b) => b - a); // Sort values high to low

console.log({ output });

output: 
    asc_1: (11) [6654, 2133, 1001, 655, 435, 432, 345, 234, 112, 34, 4]
    asc_2: (11) [6654, 2133, 1001, 655, 435, 432, 345, 234, 112, 34, 4]
    desc_1: (11) [6654, 2133, 1001, 655, 435, 432, 345, 234, 112, 34, 4]
    desc_2: (11) [6654, 2133, 1001, 655, 435, 432, 345, 234, 112, 34, 4]

When I run this code, all of them will show in descending order in the output object, although if I run them one-by-one they work as expected.

What is wrong with this code?


Solution

output.asc_1 = [...arr].sort((a, b) => (a > b ? 1 : -1)); // Sort values low to high
output.desc_1 = [...arr].sort((a, b) => (a < b ? 1 : -1)); // Sort values high to low
output.asc_2 = [...arr].sort((a, b) => a - b); // Sort values low to high
output.desc_2 = [...arr].sort((a, b) => b - a); // Sort values high to low
Community
  • 1
  • 1
Silver Ringvee
  • 5,037
  • 5
  • 28
  • 46

0 Answers0