JavaScript function for comparing arrays
by aknuds1
HTML
<script src="http://underscorejs.org/underscore.js"></script>
<script src="https://raw.github.com/douglascrockford/JSON-js/master/json2.js"></script>
<div id="body">
<h1>JavaScript Array Comparison</h1>
<ul id="results"></ul>
</div>
CSS
h1 {
font-size: 24px;
font-weight: bold;
margin-bottom: 6px;
}
#body {
margin: 30px;
}
JavaScript
function compareArrays(a, b) {
var aIsArray = Array.isArray(a),
bIsArray = Array.isArray(b),
cmp = 0;
if (!aIsArray || !bIsArray) {
throw new Error('Can\'t compare array to non-array: ' + a + ', ' + b);
}
_.find(a, function (aElem, index) {
var bElem = b[index];
if (Array.isArray(aElem) || Array.isArray(bElem)) {
cmp = compareArrays(aElem, bElem);
} else {
cmp = (aElem > bElem) - (aElem < bElem);
}
if (cmp !== 0) {
return true;
}
});
return cmp;
}
var sets = [
[
[1, 9, [5, 4, 2]],
[1, 9, [14, 5, 4]], -1],
[
[1, [1]],
[1, 1],
false],
[
[1, [2]],
[1, [1]],
1],
[
[2],
[1],
1],
[
[1],
[1],
0],
[
[],
[],
0]
];
_.each(sets, function (dataset) {
var rslt, operator, shouldThrow = false,
a, b;
try {
rslt = compareArrays(dataset[0], dataset[1]);
} catch (err) {
if (dataset[2] !== false) {
throw err;
}
// OK, should throw
shouldThrow = true;
}
if (!shouldThrow) {
if (dataset[2] === false) {
throw new Error('Comparison of ' + dataset[0] + ' and ' + dataset[1] + ' didn\'t throw');
}
if (rslt !== dataset[2]) {
throw new Error('Comparison of ' + dataset[0] + ' and ' + dataset[1] + ' failed: ' + dataset[2] + ' != ' + rslt);
}
}
if (rslt === -1) {
operator = '<';
} else if (rslt === 0) {
operator = '==';
} else if (rslt === 1) {
operator = '>';
} else {
operator = 'can\'t be compared to';
}
a = JSON.stringify(dataset[0]);
b = JSON.stringify(dataset[1]);
$('#results').append($('<li>' + a + ' ' + operator + ' ' + b + '</li>'));
});