Recently found an interview problem, using JS to implement an array merge method (requires to go to the weight). We know that the Concat method merges two arrays and returns a new array, and the new array contains each element in the old array, which is [1,2,3,2,3,4] after [three-way] combined with [2,3,4]. So how to achieve, can combine and can go heavy?
The idea is to put the value of the target array as a key into an object, and in this process, the duplicate values are filtered out so that the duplicate values are excluded.
Two arrays, a = [three-to-one], B = [2,3,4], requires the merged array to be [1,2,3,4]
Array.prototype.unique = function () {var a = {};for (var i = 0; i < this.length; i++) {if (typeof a[this[i]] = = "undefined" ) A[this[i]] = 1;} This.length = 0;for (var i in a) this[this.length] = I;return this;} var a = [1,2,3];var B = [2,3,4];var c = A.concat (b). unique ();
Two arrays, a = [three-to-one], B = [2,3,4], requires the merged array to be [1,4]
Array.prototype.unique2 = function () {var a = {},b = {},n = This.length;for (var i = 0; i < n; i++) {if (typeof (B[this[i)]) ! = "undefined") continue;if (typeof (A[this[i]]) = = "undefined") {A[this[i]] = 1;} Else{b[this[i]] = 1;delete a[this[i];}} This.length = 0;for (var i in a) this[this.length] = I;return this;} var a = [1,2,3,4];var b = [2,3,5,7];var d = a.concat (b). Unique2 ();
Reference Link: http://www.jb51.net/article/21916.htm
http://bbs.csdn.net/topics/190040118
This article is from the "Rainy Day Fly" blog, please be sure to keep this source http://lam01141127.blog.51cto.com/4074143/1633873
Using JS to implement an array merging method (requires to go to the weight)