Skip to content

Instantly share code, notes, and snippets.

@xerardoo
Created November 12, 2014 22:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xerardoo/dfb33ae174150e0642c0 to your computer and use it in GitHub Desktop.
Save xerardoo/dfb33ae174150e0642c0 to your computer and use it in GitHub Desktop.
Shim to Join to javascript arrays
/**
*@title Array.joinWith - shim by Joseph Myers 7/6/2013
*@href http://stackoverflow.com/questions/17500312/is-there-some-way-i-can-join-the-contents-of-two-javascript-arrays-much-like-i
*@notes: shim de javascript para hacer o emular "inner join" entre dos arrays de objetos
* */
if (!Array.prototype.joinWith) {
+function () {
Array.prototype.joinWith = function(that, by, select, omit) {
var together = [], length = 0;
if (select) select.map(function(x){select[x] = 1;});
function fields(it) {
var f = {}, k;
for (k in it) {
if (!select) { f[k] = 1; continue; }
if (omit ? !select[k] : select[k]) f[k] = 1;
}
return f;
}
function add(it) {
var pkey = '.'+it[by], pobj = {};
if (!together[pkey]) together[pkey] = pobj,
together[length++] = pobj;
pobj = together[pkey];
for (var k in fields(it))
pobj[k] = it[k];
}
this.map(add);
that.map(add);
return together;
}
}();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment