Example of array deduplication and flattening in Javascript

Source: Internet
Author: User
This article mainly introduces the array deduplication and paiping related information in Javascript, because this is often encountered in actual business development. This article first introduces the array judgment, it is very important to judge whether the data is an array before processing the array. If you need it, let's take a look at it. Array judgment

Before we talk about how to deduplicate and flatten arrays, let's first talk about how to judge arrays, because to process arrays, we must first determine whether the next data is an array.

First, we all know that there are only five types of js data, namely Undefined, Null, Boolean, Number, and String. The array is just an object and typeof ([]) is used. the returned result is a string of the Object. Therefore, we need to judge it by other means. Here we will talk about two methods.

First, use the instenceof method.

Instanceof is a method provided by ES5. It can be used to determine whether an instance is an instance of a certain class. For example:

[] Instenceof Array // The returned result is true.

The disadvantage of this method is that the compatibility is poor. For some earlier browsers that do not support es5.

The second method is to judge through the prototype chain.

If you understand js, you should understand that the characteristics of js language are prototype chained. All objects are inherited from objects. prototype, and prototype has the toString () method. What is the use of this toString () method? Returns the value of the current object as a string. For the first time, it may be hard to understand this sentence. For example:

Var num = 123; num. toString (); // The returned result is 123"

Have you understood this? Returns the string form of the num object value, that is, "123 ". Okay. What does this have to do with judging arrays? All objects are inherited from objects. prototype, and array. If an array is sent to an Object. in prototype, as a "value", when the toString () method is called, it should display the name of this object. This is the principle of judgment. The Code is as follows:

Object. prototype. toString. call ([]); // The result is "[object Array]".

This method is used for isArray () of a script Library such as jQuery.

Array flat

Then I decided to go straight to the topic. First, the array is flat. What is array flat? [1, [2, [3, 4], 5] Is paved as [1, 2, 3, 4, 5]. I have two ways to think about array flat. The second one is amazing. Leave some suspense.

The first is the general idea.

Traverse the array. If the array contains an array, the traversal continues until each element is completely traversed, and then the elements are inserted into the new array variable while traversing, in this way, the image is flattened. The specific code is as follows:

PanelArr = function (arr) {var newArr = []; var isArray = function (obj) {return Object. prototype. toString. call (obj) = '[object Array]';}; var dealArr = function (arr) {for (var I = 0; I

Of course, this method can also be written in Array. prototype, which is more convenient to use. The problem with this method is memory usage, because recursion will occupy a large amount of memory if the data volume is large.

Second wonderful idea

The second approach is to flat directly without looking at the array or traversing it. It sounds a little strange. How can I flat a video without traversing it? It is to use the join () method to convert the array into a string, and then remove the Regular Expression and merge it. This method is used to note that join ("") is not allowed, because if this is the case, is 13 1, 3, or 13? The Code is as follows:

var arr = [1,2,[33,43],20,19];arr.join(".").replace(/,/g,".").split("."); //["1", "2", "33", "43", "20", "19"]

Note: This method converts the data type to a string.

Array deduplication

Here is the array deduplication. For example, [1, 2, 3, 3, 4, 5, 5, 6] is changed to [1, 2, 3, 4, 5, 6]. The core of this implementation is to repeat it here. If we can quickly determine whether elements are duplicated, It is critical.

Or two ideas

First, the idea of Traversal

It is to prepare a new array variable, and traverse the variable every time before inserting to see if there are duplicates. If not, plug in. The new array generated at the end is the de-duplicated array. The sample code is as follows:

Function uniqueArr (arr) {var newArr = []; newArr. push (arr [0]); for (var I = 1; I

Second, use hash to judge

The above method with the time complexity of O (n ^ 2) is not a good method. Its bottleneck is to judge whether it is repeated, therefore, we need to replace it with a more efficient method for repeated searches. This method is hash. Why is hash retrieval the fastest? I will not repeat the data structure here.

The idea of this method is to add a hash filter between the original array and the de-duplicated array. In general, the original array data is handed over to the hash to check whether there are duplicates. If not, the data is added. The Code is as follows:

Function uniqueArr (arr) {var newArr = [], hashFilter ={}; for (var I = 0; I

I like the second one, because it is really fast to judge whether to repeat it. It can be said that it is second-out.

Summary

The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.

For more articles about the method examples of array deduplication and flat in Javascript, refer to the PHP Chinese website!

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.