Using JS to implement an array merging method (requires to go to the weight)

Source: Internet
Author: User


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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.