Как отсортировать массив внутри которого есть null?

Как отсортировать

let a = ['1 000', '30', null, '40 000', '0', null, '6']

чтобы получилось

['40 000', '1 000', '30', '6', '0', null, null]

и обратно не теряя разрядность чисел?


Ответы (2 шт):

Автор решения: entithat

Пробел в числе надо удалить, чтобы числа парсились нормально и тогда уже можно делать компарацию.

const arr = ['40 000', '1 000', '30', '6', '0', null, null, '-10'];

function comparator(a, b) {
  if (!a && b) return 1;
  if (!b && a) return -1;
  if (!b && !a) return 0;
  return b.replaceAll(' ', '') - a.replaceAll(' ', '');
}

console.log(arr.sort(comparator));
console.log(arr.reverse());

→ Ссылка
Автор решения: MoloF

const arr = ['40 000', '1 000', '30', '6', '0', null, null, '-10', 'abcd'];

function comparator(a, b) {
    if (!b) return -1;

    const num_a = +a?.replace(/\s+/g, '');
    const num_b = +b?.replace(/\s+/g, '');

    return num_b - num_a;
}

console.log(arr.sort(comparator));

→ Ссылка