Search code examples
javascriptjqueryarraysnumericsequential

Javascript\Jquery check if a numeric array values are sequential and contiguous and return incorrect values


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


Solution

  • 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; }