devnewbie
devnewbie

Reputation: 47

How to check if an array of string is sorted Ascending/Descending alphabetically?

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

["apple","summer","sun","zoo"] // ascending

Upvotes: 1

Views: 2914

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386660

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));

Upvotes: 2

pilchard
pilchard

Reputation: 12918

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));

Upvotes: 3

Related Questions