Example of array deduplication and flattening in Javascript, javascript Array
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 objecttypeof([])
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 chain. All objects are inherited fromObject.prototype
And prototype hastoString()
Method, thistoString()
What is the method used? 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? Think about all objects inherited fromObject.prototype
Array. If an array is sentObject.prototype
As a "value" intoString()
Method, it should display the object name. This is the principle of judgment. The Code is as follows:
Object. prototype. toString. call ([]); // The result is "[object Array]".
For a script library like jQueryisArray()
This method is used.
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<arr.length;i++){ isArray(arr[i]) ? dealArr(arr[i]) : newArr.push(arr[i]); } }; dealArr(arr); return newArr;};console.log(panelArr([1,[2,3]])); //[1,2,3]
Of course, this method can also be written inArray.prototype
. 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? Is to usejoin()
Method to convert the array into a string, and then remove the regular expression to merge the symbols. Note thatjoin("")
In this 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<arr.length;i++){ var repeat = false; for(var j = 0;j<newArr.length;j++){ if(arr[i] == newArr[j]){ repeat = true; } } if(!repeat){ newArr.push(arr[i]); } } return newArr;}
Second, use hash to judge
The above time complexity isO(n^2)
The method is not a good method. Its bottleneck is to judge whether to repeat it. Therefore, we need to replace it with a more efficient method to retrieve duplicates. 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 <arr. length; I ++) {if (! HashFilter [arr [I]) {// change the value corresponding to this attribute to true if it does not exist, and insert hashFilter [arr [I] = true; newArr In the deduplication array. push (arr [I]);} return newArr ;}
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.