Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Javascript Array Values are Sequential and Not Equal

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.

like image 621
James Valeii Avatar asked Dec 02 '22 13:12

James Valeii


2 Answers

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

  1. If we reached the last index, then all the elements are good.

  2. 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.

  1. current element,
  2. current index
  3. the actual array

It will keep calling the function, till the array elements run out or any of the calls to the function returns a falsy value.

like image 171
thefourtheye Avatar answered Dec 04 '22 01:12

thefourtheye


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]));
like image 28
Oleksandr T. Avatar answered Dec 04 '22 02:12

Oleksandr T.