2

I'm working with javascript\jquery and i need to check if a numeric array values are sequential and contiguous and to return incorrect values.

Example

arr = [1,2,3,10,15,30] array is sequential but only 1,2,3 are contigous...10 15 and 30 are incorrect.

UPDATE

if array is like this arr = [1,2,3,10,11,12,15,30,50] the correct sequences should be 2... 1,2,3 and 10,11,12

How can i identify multiple correct sequences?

Thanks in advance, Cla

2 Answers 2

2

You coud use Array#filter and check the predecessor or successor.

var array = [1, 2, 3, 10, 15, 30],
    result = array.filter(function (a, i, aa) {
        return aa[i - 1] + 1 !== a && a + 1 !== aa[i + 1];
    });
    
console.log(result)

EDIT for additional question.

Ther you could use two variables for the left and the right check and test id for adding an empty array and later for pushing the value to the last inner array.

var array = [1, 2, 3, 10, 11, 12, 15, 30, 50],
    result = array.reduce(function (r, a, i, aa) {
        var left = aa[i - 1] + 1 === a,
            right = a + 1 === aa[i + 1];

        if (!left && right && (!r[r.length - 1] || r[r.length - 1].length)) {
            r.push([]);
        }
        if (left || right) {
            r[r.length - 1].push(a);
        }
        return r;
    }, []);
        
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

2 Comments

if array is like this arr = [1,2,3,10,11,12,15,30,50] the correct sequences should be 2... 1,2,3 and 10,11,12 How can i identify multiple correct sequences?
please ask a new question.
1

var arr = [1,2,3,10,15,30],
arr1=[1,2,3,4,5,6,10],
arr2=[10,11,40,50];

var checkArray=function(array){
  var lastNum;
  array.forEach(function(num,index){
    if(index===0)
      lastNum=num;
    else{
      if(lastNum+1===num)
        lastNum=num;
      else
        console.log(num);
    }
  });
}
checkArray(arr);
console.log('----------------');
checkArray(arr1);
console.log('----------------');
checkArray(arr2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.