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) ); // []

JS Array

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

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog