Six de-duplicated JavaScript Array methods, javascript Array

Source: Internet
Author: User
Tags javascript array

Six de-duplicated JavaScript Array methods, javascript Array

Method 1

Without thinking, we can get the O (n ^ 2) Complexity solution. Define a variable array res to save the result and traverse the array to be de-duplicated. If this element already exists in res, it indicates it is a duplicate element. If it does not exist, it is placed in res.

 function unique(a) { var res = []; for (var i = 0, len = a.length; i < len; i++) { var item = a[i]; for (var j = 0, jLen = res.length; j < jLen; j++) { if (res[j] === item) break; } if (j === jLen) res.push(item); } return res;}var a = [1, 1, '1', '2', 1];var ans = unique(a);console.log(ans); // => [1, "1", "2"]

The code is very simple. Can it be more concise? If browser compatibility is not considered, we can use the Array. prototype. indexOf method provided by ES5 to simplify the code.

function unique(a) { var res = []; for (var i = 0, len = a.length; i < len; i++) { var item = a[i]; (res.indexOf(item) === -1) && res.push(item); } return res;}var a = [1, 1, '1', '2', 1];var ans = unique(a);console.log(ans); // => [1, "1", "2"]

Since indexOf is used, you can add filter.

function unique(a) { var res = a.filter(function(item, index, array) { return array.indexOf(item) === index; }); return res;}var a = [1, 1, '1', '2', 1];var ans = unique(a);console.log(ans); // => [1, "1", "2"]

Method 2

The first method is to compare the elements in the original array with those in the result array one by one. We can use another method to add the last element of the repeated elements in the original array to the result array.

function unique(a) { var res = a.filter(function(item, index, array) { return array.indexOf(item) === index; }); return res;}var a = [1, 1, '1', '2', 1];var ans = unique(a);console.log(ans); // => [1, "1", "2"]

Although the complexity is still O (n ^ 2), we can see that the results are different. 1 appears at the end of the array, because the result array obtains the last position of the element.

Method 3 (sort)

If only the above O (n ^ 2) solution is answered during the written test interview, it may not satisfy the interviewer. Below are several advanced solutions.

After the array is sorted by sort, theoretically the same element will be placed in the adjacent position, so you can compare the elements at the front and back positions.

function unique(a) { return a.concat().sort().filter(function(item, pos, ary) { return !pos || item != ary[pos - 1]; });}var a = [1, 1, 3, 2, 1, 2, 4];var ans = unique(a);console.log(ans); // => [1, 2, 3, 4]

But the problem arises again. 1 and "1" will be listed together, and different objects will be listed together. Because their toString () results are the same, this error will occur:

function unique(a) { return a.concat().sort().filter(function(item, pos, ary) { return !pos || item != ary[pos - 1]; });}var a = [1, 1, 3, 2, 1, 2, 4, '1'];var ans = unique(a);console.log(ans); // => [1, 2, 3, 4]

Of course, you can write this comparison function for different types that may appear in the array. But it seems a little troublesome.

Method 4 (object)

The Object in JavaScript is used as a hash table, which is also the solution of the written test a few years ago. Like sort, it can deduplicate an array completely composed of the basic Number types.

function unique(a) { var seen = {}; return a.filter(function(item) { return seen.hasOwnProperty(item) ? false : (seen[item] = true); });}var a = [1, 1, 3, 2, 1, 2, 4];var ans = unique(a);console.log(ans); // => [1, 3, 2, 4]

It is also similar to the method, because the Object's key value is of the String type, so for 1 and "1" cannot be separated, We Can slightly improve, also save the type to the key.

function unique(a) { var ret = []; var hash = {}; for (var i = 0, len = a.length; i < len; i++) { var item = a[i]; var key = typeof(item) + item; if (hash[key] !== 1) { ret.push(item); hash[key] = 1; } } return ret;}var a = [1, 1, 3, 2, '4', 1, 2, 4, '1'];var ans = unique(a);console.log(ans); // => [1, 3, 2, "4", 4, "1"]

Although it solves the annoying problems 1 and 1, there are other problems!

function unique(a) { var ret = []; var hash = {}; for (var i = 0, len = a.length; i < len; i++) { var item = a[i]; var key = typeof(item) + item; if (hash[key] !== 1) { ret.push(item); hash[key] = 1; } } return ret;}var a = [{name: "hanzichi"}, {age: 30}, new String(1), new Number(1)];var ans = unique(a);console.log(ans); // => [Object, String]

However, if all the array elements are base-type Number values, the key-Value Pair method should be the most efficient!

Method 5 (ES6)

ES6 deploys the Set and Array. from methods, which is too powerful! If the browser supports this, you can:

function unique(a) { return Array.from(new Set(a));}var a = [{name: "hanzichi"}, {age: 30}, new String(1), new Number(1)];var ans = unique(a);console.log(ans); // => [Object, Object, String, Number]

_. Unique

Finally, let's take a look at underscore's implementation method. underscore encapsulates this into the _. unique Method and calls it through _. unique (array, [isSorted], [iteratee]). The first parameter is required, which is an array that requires deduplication. The second parameter is optional. If the array is ordered, a Boolean value of true can be input. The third parameter is optional, if you need to deduplicate the result of array iteration, You can input an iteration function. Array Element deduplication is based on the = Operator.

In fact, it is very simple. The Implementation Method in underscore is similar to the above method.

Let's look at its core code:

For (var I = 0, length = getLength (array); I <length; I ++) {var value = array [I], // If an iteration function is specified, // iterate computed = iteratee for each element in the array? Iteratee (value, I, array): value; // if it is an ordered array, the current element only needs to be compared with one element. // use the seen variable to save the previous element if (isSorted) {// if I = 0, direct push // otherwise, compare whether the current element is equal to the previous one if (! I | seen! = Computed) result. push (value); // seen saves the current element for the next comparison of seen = computed;} else if (iteratee) {// if the element value of computed is not in seen [], if (! _. Contains (seen, computed) {seen. push (computed); result. push (value) ;}} else if (! _. Contains (result, value) {// if you do not need iterative function compute, you do not need to use the seen [] variable result. push (value );}}

The elements in the array are traversed cyclically. For each element, if the array is ordered, it is compared with the previous element. If it is the same, it has already appeared and is not added to the result array, otherwise, Add. If an iteration function exists, the value after the input iteration function is calculated, the pair value is de-duplicated, and called. the contains method, and the core of this method is to call. the indexOf method is similar to the method we mentioned above.

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.