I read this, but it doesn't apply (and/or, I can't figure out how to adapt the solutions). I also found this, but I don't want to change the array - I just want to check the information. I was unable to adapt the solutions to fit my needs.
I want to find out of the values in a Javascript Array are Sequential.
For example - I have an array of UNIX timestamps
var ts = [1451772000, 1451858400, 1452031200]
I want to return true
if they are sequential (lower to higher values) and false
if they are not sequential. I would also like to return false
if there are duplicate values.
You can use Array.prototype.every
, like this
var data = [1451772000, 1451858400, 1452031200];
console.log(data.every((num, i) => i === data.length - 1 || num < data[i + 1]));
The same can be written with a normal function, like this
console.log(data.every(function(num, index) {
return index === data.length - 1 || num < data[index + 1];
}));
There are basically only two conditions to take care here
If we reached the last index, then all the elements are good.
If it is not the last element, then the current number should be strictly lesser than the next element.
This expression takes care of the above two conditions.
i === data.length - 1 || num < data[i + 1]
The every
function calls the function passed to it, for each and every value of the array, with three parameters.
It will keep calling the function, till the array elements run out or any of the calls to the function returns a falsy value.
You can use simple for-loop
like this
function isSequential(data) {
for (var i = 1, len = data.length; i < len; i++) {
// check if current value smaller than previous value
if (data[i] < data[i - 1]) {
return false;
}
}
return true;
}
console.log(isSequential([1]));
console.log(isSequential([1, 2, 3, 4]));
console.log(isSequential([1, 5, 3, 4]));
console.log(isSequential([1451772000, 1451858400, 1452031200]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With