Monkey Raptor

Thursday, September 8, 2016

JavaScript: Check If Array Elements (Numbers) Are in Order

This is a snippet to check whether array elements (which all are numbers) are ordered (ascending / descending).

In ascending order, for instance, we have these arrays to test:

  • [0, 1, 1, 1, 2, 5, 4, 100, 2]
  • [0, 1, 2, 3, 6, 4, 5, 7]
  • [15, 16, 17, 18, 19, 20]
  • [2, 3, 4, 32, 33, 34, 35]

In descending order, we have these arrays to test:

  • [100, 99, 99, 98, 97, 99]
  • [4, 3, 2, 1, 0]
  • [21, 20, 19, 4, 3]
  • [54, 52, 20, 27]

So then, let's go type a JavaScript function. It goes like this, you can read the comments to understand the variables:


Then we define the either array above as a variable, like so:


Ascending

results:

var array = [0, 1, 1, 1, 2, 5, 4, 100, 2];
var result = checkOrderedArrElm(array);
// console.log(result) -> false
var array = [0, 1, 2, 3, 6, 4, 5, 7];
var result = checkOrderedArrElm(array);
// console.log(result) -> false
var array = [15, 16, 17, 18, 19, 20];
var result = checkOrderedArrElm(array);
// console.log(result) -> true
var array = [2, 3, 4, 32, 33, 34, 35];
var result = checkOrderedArrElm(array);
// console.log(result) -> true

Descending

results (activate the b argument):

var array = [100, 99, 99, 98, 97, 99];
var result = checkOrderedArrElm(array, 1);
// console.log(result) -> false
var array = [4, 3, 2, 1, 0];
var result = checkOrderedArrElm(array, 1);
// console.log(result) -> true
var array = [21, 20, 19, 4, 3];
var result = checkOrderedArrElm(array, 1);
// console.log(result) -> true
var array = [54, 52, 20, 27];
var result = checkOrderedArrElm(array, 1);
// console.log(result) -> false

This function works only for number (integer / float) type of array element. Other type besides number will be ignored.

And this doesn't check the detailed sequence difference. It only checks whether the current element is larger or smaller than the next one (or the same as the next one).
To be more detailed, create algebraic something to do the checking.

And to remove the same elements checking, change the operator >= (greater than or equal to) to just > (greater than) or <= (less than or equal to) to just < (less than).

Anyway, there's that constructor keyword. It's only available for input argument that has value besides undefined. Therefore, the constructor filter is placed after the undefined filter.


If you need to map it to letter (a-z) or unicode or bunch of others, it's the same idea, but you need to create your own mapping for the input argument to be checked, so the comparison operator (less / greater than or equal to) works.


This basic function can be translated to other programming languages.

JavaScript: Check If Array Elements (Numbers) Are in Order
http://monkeyraptor.johanpaul.net/2016/09/javascript-check-if-array-elements.html

No comments

Post a Comment

Tell me what you think...