Let's say I have an array of integers in Javascript, and I would like to check if all its values are in ascending order. I want to save the array key in another array if the algorithm finds a value that is lower (or equal), not only comparing the nearest previous one, but also comparing any value that is before it. I have done this:
arr = [], nonvalid = []; for (var j = 1; j < arr.length; j++){ if ( arr[j+1] <= arr[j] ){ nonvalid.push(j); } }
Obviously, the above algorithm only checks for values that are lower than the previous ones.
An array may contain the following values:
arr = 1, 2, 3, 10, 5 , 11, 12, 2 , 4 , 25
Invalid values are bold. If I run the above cycle, he will not “catch” the second last ( 4 ), because he will be larger than his closest left brother, but not as high as all his left brothers.
EDIT:
Tried the following solutions, and none of them returned all invalid values for this array, except mine .:(
They returned the last two values correctly, but not the second. However, I do not understand why.
[24398, 24397 , 25004, 25177, 26302, 28036, 29312, 29635, 29829, 30476, 32595, 33732, 34995, 36047, 36363, 37310, 38022, 38882, 40746, 41212, 42846, 43588, 44029, 44595, 44846 , 45727, 46041, 47293, 48002, 48930, 49858, 51184, 51560, 53895, 54247, 54614, 55713, 56813, 57282, 57480, 57875, 58073, 58403, 60321, 61469, 62051, 62310, 62634, 63217, 643217, 643217. , 65413, 65677, 65940, 66203, 66572, 67957, 68796, 68964, 69098, 69233, 69435, 69759, 71496, 72577, 72823, 73007, 73252, 73743, 73866, 76405, 77037, 77416, 77669, 79691, 8088. , 81339, 81794, 82067, 82431, 83244, 84861, 86836, 88632, 89877, 90296, 91049, 91885, 92351, 92614, 93141, 93733, 93930, 94531, 95206, 95882, 96895, 97732, 97973, 99261, 99261, 99261, 99261, 99261. , 99583, 100332, 100599, 101666, 102066, 102600, 103504, 104432, 105174, 107216, 109085, 110181, 110679, 111177, 111988, 112553, 113005, 113457, 600 , 600 ]