Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!