find the longest sorted sequence in javascript

One way to find the longest sorted sequence in JavaScript is to iterate through the array and keep track of the current sequence length and the longest sequence length seen so far. We can also keep track of the current sequence start index so that we can return the longest sorted subarray.

Here's the code:

index.tsx
function longestSortedSequence(arr) {
  let longestSeqLength = 1;
  let currentSeqLength = 1;
  let longestSeqStartIndex = 0;
  let currentSeqStartIndex = 0;

  for (let i = 1; i < arr.length; i++) {
    if (arr[i] >= arr[i-1]) {
      // current element is part of the sorted sequence
      currentSeqLength++;
    } else {
      // current element is not part of the sorted sequence
      if (currentSeqLength > longestSeqLength) {
        longestSeqLength = currentSeqLength;
        longestSeqStartIndex = currentSeqStartIndex;
      }
      currentSeqLength = 1;
      currentSeqStartIndex = i;
    }
  }

  // handle the case where the longest sorted sequence is at the end of the array
  if (currentSeqLength > longestSeqLength) {
    longestSeqLength = currentSeqLength;
    longestSeqStartIndex = currentSeqStartIndex;
  }

  return arr.slice(longestSeqStartIndex, longestSeqStartIndex + longestSeqLength);
}
918 chars
30 lines

To use this function, simply pass in an array of numbers:

index.tsx
const arr = [1, 2, 3, 1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4];
const longestSeq = longestSortedSequence(arr);
console.log(longestSeq); // [1, 2, 3, 4, 5]
150 chars
4 lines

gistlibby LogSnag