Compare Simple Array Content
yield true if the array contents are equal irrespective of ordering.
by Paul Whipp
HTML
<table>
<thead>
<tr>
<th>arrayA</th>
<th>arrayB</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>[<span id="testA">?</span>]</td>
<td>[<span id="testB">?</span>]</td>
<td><span id="result">?</span></td>
</tr>
</tbody>
</table>
Babel + JSX
const testA = [1, 1, 2];
const testB = [1, 2, 1];
const arrayContentsEqual = (arrayA, arrayB) => {
if (arrayA.length !== arrayB.length) {
return false}
const refCount = (function() {
const refCountMap = {};
const refCountFn = (elt, count) => {refCountMap[elt] = (refCountMap[elt] || 0) + count}
refCountFn.isZero = () => {
for (let elt in refCountMap) {
if (refCountMap[elt] !== 0) {
return false}}
return true}
return refCountFn})()
arrayB.map(eltB => refCount(eltB, 1));
arrayA.map(eltA => refCount(eltA, -1));
return refCount.isZero()}
const show = () => {
const [testAElt, testBElt, resultElt] = ["testA", "testB", "result"].map(
id => document.getElementById(id))
testAElt.innerHTML = testA.toString();
testBElt.innerHTML = testB.toString();
resultElt.innerHTML = (arrayContentsEqual(testA, testB)) ? "true" : "false"}
show();