JS: Split Array 📜
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); }; // s------------------------------ /* xah_is_obj_equal(xaa, xbb) Return true if every enumerable property keys and values are equal. (symbol keys are ignored), nested objects are compared the same way. Order of properties 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. * Map and Set object are not treated in a special way here. You should not use this function to compare them. * If one of the argument is not object type, result is same as triple equal operator. URL http://xahlee.info/js/js_test_object_equality.html Created: 2022-10-13 Version: 2026-01-21 */ const xah_is_obj_equal = (xaa, xbb) => { if (xaa === xbb) return true; if ((typeof xaa !== "object") || (typeof xbb !== "object")) return xaa === xbb; const xisArrayA = Array.isArray(xaa); const xisArrayB = Array.isArray(xbb); if (xisArrayA && xisArrayB) { if (xaa.length !== xbb.length) return false; else return xaa.every((v1, ii) => xah_is_obj_equal(v1, xbb[ii])); } else { const xkeysA = Object.keys(xaa); const xkeysB = Object.keys(xbb); if (xkeysA.length !== xkeysB.length) return false; return xkeysA.every((kk) => xah_is_obj_equal(xaa[kk], xbb[kk])); } }; // s------------------------------ // test console.assert((xah_is_obj_equal(xah_split_array([3, 0, 5], (x) => x === 0), [[3], [5]])) === true); console.assert((xah_is_obj_equal(xah_split_array([3, 0, 0, 5], (x) => x === 0), [[3], [5]])) === true); console.assert((xah_is_obj_equal(xah_split_array([0, 1, 5], (x) => x === 0), [[1, 5]])) === true); console.assert((xah_is_obj_equal(xah_split_array([0, 1, 5, 0], (x) => x === 0), [[1, 5]])) === true); console.assert((xah_is_obj_equal(xah_split_array([], (x) => x === 0), [])) === true);