This feels like the kind of problem that has an extremely elegant solution. But my code is mechanical and straightforward. Not bad but I'm interested if there's something nicer.
Performance is not really an issue. I'm looking for elegant/shorter, not faster.
No underscore.js please; it's not worth fighting my coworkers to get another third-party library in there, especially when it duplicates so much ES5. Speaking of which, we work in an ES5-only environment so use all the array extras you want.
function getIds(array) {
// We have added `Array.prototype.unique`; it does what you'd expect.
return array.map(function (x) { return x.id; }).unique().sort();
}
function areDifferentByIds(a, b) {
var idsA = getIds(a);
var idsB = getIds(b);
if (idsA.length !== idsB.length) {
return true;
}
for (var i = 0; i < idsA.length; ++i) {
if (idsA[i] !== idsB[i]) {
return true;
}
}
return false;
}
containSameIds
and just swapreturn true
withreturn false
. I personally would convert arrays to hash sets and then iterate over one, then another (if sizes are the same). I would not try to make the function too short at the expense of readability. \$\endgroup\$idsA = ["x"]
,idsB = ["x", "y"]
. \$\endgroup\$!==
should be<
:-P \$\endgroup\$