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

Time:12-04

how to check if an array is sorted ascending or descending alphabetically or unsorted e.g ["apple","summer","sun","zoo"] in js

CodePudding user response:

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 'descending' or 'ascending' accordingly, otherwise return 'unsorted'.

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

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

  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));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

If you're just trying to check it, you could use

console.log(arrayName);

Then see what the result is in your console.

  • Related