This is fast, collates any number of arrays, and works with both numbers and strings.
function collate(a){ // Pass an array of arrays to collate into one array var h = { n: {}, s: {} }; for (var i=0; i < a.length; i++) for (var j=0; j < a[i].length; j++) (typeof a[i][j] === "number" ? h.n[a[i][j]] = true : h.s[a[i][j]] = true); var b = Object.keys(h.n); for (var i=0; i< b.length; i++) b[i]=Number(b[i]); return b.concat(Object.keys(h.s)); } > a = [ [1,2,3], [3,4,5], [1,5,6], ["spoon", "fork", "5"] ] > collate( a ) [1, 2, 3, 4, 5, 6, "5", "spoon", "fork"]
If you don't need to distinguish between 5 and "5", then
function collate(a){ var h = {}; for (i=0; i < a.length; i++) for (var j=0; j < a[i].length; j++) h[a[i][j]] = typeof a[i][j] === "number"; for (i=0, b=Object.keys(h); i< b.length; i++) if (h[b[i]]) b[i]=Number(b[i]); return b; } [1, 2, 3, 4, "5", 6, "spoon", "fork"]
will do.
And if you don't mind (or would prefer) all values ending up as strings anyway then just this:
function collate(a){ var h = {}; for (var i=0; i < a.length; i++) for (var j=0; j < a[i].length; j++) h[a[i][j]] = true; return Object.keys(h) } ["1", "2", "3", "4", "5", "6", "spoon", "fork"]
If you don't actually need an array, but just want to collect the unique values and iterate over them, then (in most browsers (and node.js)):
h = new Map(); for (i=0; i < a.length; i++) for (var j=0; j < a[i].length; j++) h.set(a[i][j]);
It might be preferable.