Skip to content

Instantly share code, notes, and snippets.

@CatTail
Created November 29, 2012 05:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CatTail/4167036 to your computer and use it in GitHub Desktop.
Save CatTail/4167036 to your computer and use it in GitHub Desktop.
Javascript array concatenation
// Following concat function concatenate javascript arrays
// It consider three more factor then normal Array.prototype.concat:
// 1. eliminate common element
// 2. escape null and undefined
// 3. deal with element being an array
var arr1 = ['a'];
var arr2 = ['b', 'c'];
var arr3 = ['c', ['d'], 'e', undefined, null];
// return object classname
var classof = function(o){
if (o === null) { return "null"; }
if (o === undefined) { return "undefined"; }
var className = Object.prototype.toString.call(o).slice(8,-1);
return className;
};
var concat = (function(){
// concat arr1 and arr2 without duplication.
var concat_ = function(arr1, arr2) {
for (var i=arr2.length-1;i>=0;i--) {
// escape undefined and null element
if (arr2[i] === undefined || arr2[i] === null) {
continue;
}
// recursive deal with array element
// can also handle multi-level array wrapper
if (classof(arr2[i]) === 'Array') {
for (var j=arr2[i].length-1;j>=0;j--) {
concat_(arr1, arr2[i][j]);
}
continue;
}
arr1.indexOf(arr2[i]) === -1 ? arr1.push(arr2[i]) : 0;
}
};
// concat arbitrary arrays.
// Instead of alter supplied arrays, return a new one.
return function(arr) {
var result = arr.slice();
for (var i=arguments.length-1;i>=1;i--) {
concat_(result, arguments[i]);
}
return result;
};
}());
console.log( arr1.concat(arr2, arr3) );
// result: [ 'a', 'b', 'c', 'c', [ 'd' ], 'e', undefined, null ]
console.log( concat(arr1, arr2, arr3) );
// result: [ 'a', 'e', 'd', 'c', 'b' ]
delete arr3[2];
console.log( concat(arr1, arr2, arr3) );
// result: [ 'a', 'd', 'c', 'b' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment