0

how to check if an array is sorted ascending or descending alphabetically or unsorted.

["apple","summer","sun","zoo"] // ascending
pilchard
  • 12,414
  • 5
  • 11
  • 23
devnewbie
  • 37
  • 3
  • Does this answer your question? [Sort a string date array](https://stackoverflow.com/questions/30691066/sort-a-string-date-array) – Elikill58 Dec 03 '21 at 22:03

2 Answers2

1

You can iterate over the array and track the results of String#localeCompare() called on all neighbors.

Then simply check if all results are either <= 0 or >=0 and return 'ascending' or 'descending' accordingly, otherwise return 'unsorted'.

function getSortDirection(arr) {
  const c = [];
  for (let i = 1; i < arr.length; i++) {
    c.push(arr[i - 1].localeCompare(arr[i]));
  }

  if (c.every((n) => n <= 0)) return 'ascending';
  if (c.every((n) => n >= 0)) return 'descending';

  return 'unsorted';
}

const ascending = ['apple', 'summer', 'sun', 'zoo'];
const descending = ['zoo', 'sun', 'summer', 'apple'];
const unsorted = ['summer', 'zoo', 'apple', 'sun'];

console.log(ascending, '–', getSortDirection(ascending));
console.log(descending, '–', getSortDirection(descending));
console.log(unsorted, '–', getSortDirection(unsorted));
pilchard
  • 12,414
  • 5
  • 11
  • 23
1

You could check the item with the previous item or return true for the first item.

const
    asc = (b, i, { [i - 1]: a }) => !i || a <= b,
    array = ["apple", "summer", "sun", "zoo"];

console.log(array.every(asc));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392