bedrockcoder
bedrockcoder

Reputation: 23

TypeScript array of numbers is always sorted - even when it's not

I have made a function that checks whether an array of numbers is sorted:

const isSorted = (values: number[]) => {
    return values === values.sort((a, b) => a - b);
};

isSorted([4, 2, 8, 7, 3, 10, 1, 5, 9, 6]); // Returns `true`

As you can see, the function returns true no matter what the input is, so how could I make the function work as it should?

I am using:

Upvotes: 0

Views: 151

Answers (4)

Todd Skelton
Todd Skelton

Reputation: 7239

Loop through the array and check if any of the values are greater than the next value. That should be the fastest way to tell if it's sorted.

const isSorted = (values: number[]) => {
  let sorted = true;

  for (int i = 0; i < values.length - 1; i++) {
    if (values[i] > values[i+1]) {
      sorted = false;
      break;
    }
  }

  return sorted;
}

Upvotes: 0

Dee Jai
Dee Jai

Reputation: 1

In the sample shared values getting compared with itself. In order to achieve desired you need to implement the sort manually.

Upvotes: 0

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

You are comparing values with itself. Hence true. You will have to manually check that each element on a given index in the sorted array is the same as each element from the values array on same index. Something like this:

const isSorted = (values: number[]) => {
    let sorted = values.slice().sort((a, b) => a - b)
    return isEqual(values, sorted);
};

isEqual could come from here. Answer by @Todd seems faster though indeed, but at least my answer shows some of the faults you had in your approach.

Upvotes: 1

Anatoly
Anatoly

Reputation: 22758

sort method sorts elements of an array in-place and of course returns the original array.

You need to make a copy of the original array if you wish that it should stay unsorted.

Upvotes: 0

Related Questions