JavaScript: Split Array

By Xah Lee. Date: . Last updated: .

Here's a function that splits a array.

/* [
xah_split_array(array37656, f)
return a nested array, by split the array at elements where f return true.
Such element is not included in the result.
http://xahlee.info/js/js_split_array.html
version 2018-04-07
] */
const xah_split_array = ((array37656, f_test) => {
  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

console.log(
  xah_is_array_equal(xah_split_array([3, 0, 5], ((x) => x === 0)), [[3], [5]]),
);

console.log(
  xah_is_array_equal(
    xah_split_array([3, 0, 0, 5], ((x) => x === 0)),
    [[3], [5]],
  ),
);

console.log(
  xah_is_array_equal(xah_split_array([0, 1, 5], ((x) => x === 0)), [[1, 5]]),
);

console.log(
  xah_is_array_equal(xah_split_array([0, 1, 5, 0], ((x) => x === 0)), [[1, 5]]),
);

console.log(xah_is_array_equal(xah_split_array([], ((x) => x === 0)), []));
JS in Depth
XAH  BUY NOW