Home > Enterprise >  .sort not sorting from lowest to highest
.sort not sorting from lowest to highest

Time:02-20

while (true) {
  let texts = await page.evaluate(() => {
    let data = [];
    let elements = document.getElementsByClassName("my-2 card__price tw-truncate");
    for (var element of elements) {

      var floor = Number(element.textContent.split("SOL")[0])
      data.push(floor)
    }

    return data.sort()
  });
  floorpricearray = texts
  if (texts !== undefined) {

    console.log(floorpricearray)
  }
}

The output

[
      10,   11,    5.3,    5.3,
    5.38,  5.4,    5.4, 5.4321,
  5.4321,  5.5, 5.6942,    5.8,
    5.95,  6.2,      7,   7.95,
    7.99, 8.05,    8.3,      9
]

CodePudding user response:

You need to give the native .sort method a comparator function like so, otherwise the values will converted to strings and then sorted by the characters ASCII value.

data.sort((a, b) => {
  return a - b;
});

CodePudding user response:

You can try this

var a = [10, 11, 5.3, 5.3,
  5.38, 5.4, 5.4, 5.4321,
  5.4321, 5.5, 5.6942, 5.8,
  5.95, 6.2, 7, 7.95,
  7.99, 8.05, 8.3, 9
];
a.sort(function(a, b) {
  return a - b;
});
alert(a);

CodePudding user response:

It is sorting the array considering the array elements as string. To get it sorted from lowest to highest it needs to be a number.

  • Related