JS: Split Array

By Xah Lee. Date: . Last updated: .

Here's a function that splits a array.

const xah_split_array = ((array37656, f_test) => {
/* [
given a array
array37656,
return a nested array.
f_test is a function. if it returns true on a element, it's a split point.
split point is not included in the result.

JS: Split Array
http://xahlee.info/js/js_split_array.html
version 2018-04-07
] */
    const result = [];
    let lastFound = 0;

    for (let i = 0; i < array37656.length; i++) {
        if ( f_test(array37656[i]) ) {
            result . push ( array37656.slice ( lastFound, i));
            lastFound = i+1;
        }
    }

    result . push ( array37656.slice ( lastFound));

    return result.filter ( ((x) => x.length !== 0) );
});

// test

const f = ((x) => x === 0);

console.log ( xah_split_array([3,0,5], f) ); // [ [ 3 ], [ 5 ] ]
console.log ( xah_split_array([3,0,0,5], f) ); // [ [ 3 ], [ 5 ] ]
console.log ( xah_split_array([0,1,5], f) ); // [ [ 1, 5 ] ]
console.log ( xah_split_array([0,1,5,0], f) ); // [ [ 1, 5 ] ]
console.log ( xah_split_array([], f) ); // []

Array Topic

  1. JS: Array Basics
  2. JS: Understand JS Array
  3. JS: Create Array
  4. JS: Sparse Array
  5. JS: Array-Like Object
  6. JS: Array How-To
  7. JS: Array Object
  8. JS: Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon