JS: Split Array 🚀

By Xah Lee. Date: . Last updated: .

Here is a function that splits a array.

/*
xah_split_array(xary, f)
return a nested array, by split the array at elements where f return true.
Such element is not included in the result.
URL http://xahlee.info/js/js_split_array.html
version 2018-04-07
*/
const xah_split_array = ((xary, f_test) => {
  const xresult = [];
  let xlastFound = 0;
  for (let i = 0; i < xary.length; i++) {
    if (f_test(xary[i])) {
      xresult.push(xary.slice(xlastFound, i));
      xlastFound = i + 1;
    }
  }
  xresult.push(xary.slice(xlastFound));
  return xresult.filter((x) => x.length !== 0);
});

// ssss---------------------------------------------------
// test

/*
xah_is_equal(xx, yy)
Return true if 2 objects xx yy are equal.
if one of the argument is not object type, result is same as triple equal operator.
Equal here means every enumerable property values of object are equal. (symbol keys are ignored).
Order does not matter.
Argument may be Object, true array, Array-like objects.
For true arrays, index are considered as key. (and order matters.)
Array-like objects are considered the same as object.

URL http://xahlee.info/js/js_test_object_equality.html
version 2022-10-13
 */
const xah_is_equal = ((xx, yy) => {
  if (xx === yy) return true;
  if ((typeof xx !== "object") || (typeof yy !== "object")) {
    return xx === yy;
  }
  if (Array.isArray(xx) && Array.isArray(yy)) {
    if (xx.length !== yy.length) {
      return false;
    } else {
      return xx.every((v1, ii) => xah_is_equal(v1, yy[ii]));
    }
  } else {
    const keys1 =
      ((Array.isArray(xx)) ? Object.keys(xx) : Object.keys(xx).sort());
    const keys2 =
      ((Array.isArray(yy)) ? Object.keys(yy) : Object.keys(yy).sort());
    if (keys1.length !== keys2.length) return false;
    if (!keys1.every((k, i) => (k === keys2[i]))) return false;
    return keys1.every((kk) => xah_is_equal(xx[kk], yy[kk]));
  }
});

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

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

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

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

console.log(xah_is_equal(xah_split_array([], (x) => x === 0), []));
BUY ΣJS JavaScript in Depth