0

Can anyone help I am nearly there I can get the code to return true for the first 2 test below, but not return false for the next 2 tests, what I need to do is to check that all the numbers in the array are in ascending order so every element number is greater than the last for the length of the array. Any ideas? Kind regards Jon.

 Test.expect(inAscOrder([1, 2, 4, 7, 19])
 Test.expect(inAscOrder([1, 2, 3, 4, 5])
 Test.expect(!inAscOrder([1, 6, 10, 18, 2, 4, 20])
 Test.expect(!inAscOrder([9, 8, 7, 6, 5, 4, 3, 2, 1])

function inAscOrder(arr) {

let result = false;

for (let i = 0; i <= arr.length; i++) {
for (let k = 0; k <= arr.length; k++) {
    if (arr[i] < arr[k+1]) {
     result = true;
            
    } 
   }
  }

return result; }

2
  • You were close, see this answer. Commented Sep 7, 2021 at 14:41
  • you can use functional way to make life easier Commented Sep 7, 2021 at 14:46

4 Answers 4

1

You were very close to answer

function inAscOrder(arr) {
    let result = true;

    for (let i = 0; i <= arr.length; i++) {
        if (arr[i] > arr[i+1]) {
            result = false;
            break;   
        }
    }
    return result; 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Armand I went down the single for loop route first of all and all I way missing was knowing how to compare the current iteration of the array i to the next element using i+1 in [ ]. Awesome thank you for your help much appreciated kind regards Jon.
1

Try this,

You can use the functional way instead.

const inAscOrder = arr => arr.slice(1).every((elem,i) => elem > arr[i]);
console.log(inAscOrder([1,2,5]));

2 Comments

This is returning false for given input
@Mohitkumar editted the answer, now passes all testt
0

The easiest way to compare two arrays, is to convert them to a strings and then compare the strings.

const isAscending = (arr) => arr.join("") == arr.sort((a, b) => a - b).join("");

console.log(isAscending([1, 2, 4, 7, 19]));
console.log(isAscending([1, 2, 3, 4, 5]));
console.log(isAscending([1, 6, 10, 18, 2, 4, 20]));
console.log(isAscending([9, 8, 7, 6, 5, 4, 3, 2, 1]));

Comments

0

For every element in the array, return true if it's the first element or it's greater than the previous element.

const isAscending = (arr) => arr.every((el, i, arr) => i === 0 || el > arr[i - 1]);

console.log(isAscending([1, 2, 4, 7, 19]));
console.log(isAscending([1, 2, 3, 4, 5]));
console.log(isAscending([1, 6, 10, 18, 2, 4, 20]));
console.log(!isAscending([9, 8, 7, 6, 5, 4, 3, 2, 1]));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.