Skip to content

Instantly share code, notes, and snippets.

@akiva
Created December 4, 2014 09:32
Show Gist options
  • Save akiva/a65457e11c3312a99bfa to your computer and use it in GitHub Desktop.
Save akiva/a65457e11c3312a99bfa to your computer and use it in GitHub Desktop.
// Merge arrays into single array, removing duplicates. This version
// removes objects that are duplicates by values, not memory pointers,
// ie. `{ foo: 'bar' }` and `{ foo: 'bar' }` are seen as duplicates
function mergeArrays() {
var args = arguments;
var hash = {};
var arr = [];
for (var i = 0; i < args.length; i++) {
for (var j = 0; j < args[i].length; j++) {
if (hash[args[i][j]] !== true) {
arr[arr.length] = args[i][j];
hash[args[i][j]] = true;
}
}
}
return arr;
}
// => [1, 2, 3, 4, 5, 6, 7, 8]
console.log(
mergeArrays(
[1,2,3,4,5],
[1,2,3,4,5,6],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7,8]
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment