bug: setUnion returns wrong element order when sets overlap (intersection placed at end)
Author: JSap0914Created Jun 30, 2026Updated Jun 30, 2026
Bug Description
math.setUnion() produces incorrect results whenever the two input sets share any elements. The intersection is placed at the end of the output rather than in its correct sorted position.
Reproduction
math.setUnion([1, 2, 3, 4], [3, 4, 5, 6])
// actual: [1, 2, 5, 6, 3, 4]
// expected: [1, 2, 3, 4, 5, 6] ← as documented in the JSDoc
math.setUnion([1, 2], [2, 3])
// actual: [1, 3, 2]
// expected: [1, 2, 3]The JSDoc example explicitly documents setUnion([1, 2, 3, 4], [3, 4, 5, 6]) → [1, 2, 3, 4, 5, 6].
Root Cause
The implementation uses:
return concat(setSymDifference(b1, b2), setIntersect(b1, b2))setSymDifference returns [a-only elements, b-only elements], so the result is
[a-only, b-only, a∩b] — the intersection lands at the end instead of between the two halves.
Expected Behaviour
Union should return the sorted result: a-only elements ++ common elements ++ b-only elements, i.e.:
return concat(concat(setDifference(b1, b2), setIntersect(b1, b2)), setDifference(b2, b1))Environment
- mathjs version: develop branch
Source: josdejong/mathjs