-1

I have a snippet for my examples, i need best practice of sorting algorithm with asc, desc convertion. this snippet have many complex for according to job, because string numbers always required in array. how can i simplify this snippet.

const data = [['aaa','22'], ['aba','23'],['baa','12'],['caa','122']]

console.log(data)
console.log('\n')

var columnIndex = 0;
var order = 'DESC';

data.sort((a, b) => {
  if (!Number.isInteger(Number.parseInt(a[columnIndex]))) {
      if (a[columnIndex] < b[columnIndex]) {
          return order === "ASC" ? -1 : 1;
      }
      if (a[columnIndex] > b[columnIndex]) {
          return order === "ASC" ? 1 : -1;
      }
      return 0;
  }
  else {
      return order === "ASC" ? (Number(a[columnIndex].match(/(\d+)/g)) - Number((b[columnIndex].match(/(\d+)/g)))) : ( Number((b[columnIndex].match(/(\d+)/g))) - Number(a[columnIndex].match(/(\d+)/g)));
  }
});
console.log(data);
Shavell
  • 21
  • 1

1 Answers1

0

You can use partial application with a curried function like sortBy() below to determine sort order and criteria without relying on global variables. I've even provided usage in an event listener that automatically updates the output whenever the inputs are changed:

const data = [['aaa', 22], ['aba', 23], ['baa', 12], ['caa', 122]];
const sortBy = (o, i) => (a, b) => (-(a[i] < b[i]) || +(a[i] > b[i])) * o;

function update () {
  const [order, index] = Array.from(
    document.querySelectorAll('select'),
    input => Number(input.value)
  );
  const sort = sortBy(order, index);

  document.querySelector('#json').textContent = JSON.stringify(data.sort(sort));
}

document.body.addEventListener('input', update);

update();
<select name="order" value="1">
  <option value="1">Ascending</option>
  <option value="-1">Descending</option>
</select>

<select name="index" value="0">
  <option value="0">String</option>
  <option value="1">Number</option>
</select>

<pre id="json"></pre>

This is a modification of my answer to Sort array of objects by string property value, which contains much more explanation about how sortBy() works.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • but even for if i don't use string numbers – Shavell Nov 28 '18 at 08:46
  • If you want a recommendation for best practice, don't store your numbers as strings. JSON format allows numeric values, so use them. Strings are sorted lexicographically, so `'122' < '22'` because `'1' < '2'`. – Patrick Roberts Nov 28 '18 at 08:49