Home Web Front-end JS Tutorial Examples of methods for deduplicating and flattening arrays in Javascript

Examples of methods for deduplicating and flattening arrays in Javascript

Feb 03, 2017 pm 01:01 PM

Judgment of Arrays

Before talking about how to deduplicate and flatten arrays, let’s first talk about how to judge arrays, because in order to process arrays, of course, you must first judge whether the data passed is an array. .

First of all, we all know that there are only 5 data types in js, namely Undefined, Null, Boolean, Number and String. The array is just an object. The result returned by typeof([]) is a string of Object. , so we need to judge it by other means, here are two methods.

The first method is to use instanceof

Instanceof is a method provided by ES5, which can be used to determine whether an instance is an instance of a certain class, for example:

[] instenceof Array
//返回结果是true
Copy after login

The disadvantage of this method is that it has poor compatibility. Some lower version browsers that do not support ES5 will be confused.

The second method is to judge through the prototype chain

If you understand js, you should understand that the characteristic of the js language is the prototype chain, and all objects inherit from Object.prototype , and there is a toString() method on the prototype. What is this toString() method used for? It returns the value of the current object in the form of a string. You may not understand this sentence when you read it for the first time. Here is an example:

var num = 123;
num.toString(); //返回结果为"123"
Copy after login

Do you understand it a little bit? It returns the string form of the object value num, which is "123". Okay, what does this have to do with judging arrays? Think about it, all objects inherit from Object.prototype, and so do arrays. If you send an array to Object.prototype as a "value" and call the toString() method, it should display the name of the object. Ah, this is the principle of judgment. The code is as follows:

Object.prototype.toString.call([]); //结果是"[object Array]"
Copy after login

This is the method used by isArray() of script libraries like jQuery.

Array Patting

After talking about it, let’s go straight to the topic. First, array Patting. What is Array Patting? Just pave [1,[2,[3,4],5]] into [1,2,3,4,5]. I have two ideas about array flattening. The second one is rather weird, so I’ll leave you with some suspense, haha.

The first is the conventional idea

Traverse the array. If there is an array inside the array, continue to traverse it until every element is traversed, and then stuff it in while traversing. In the new array variable, the flattening is completed. 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]
Copy after login

Of course, this method can also be written in Array.prototype and used. more convenient. One problem with this method is memory usage, because recursion will occupy a lot of memory if the amount of data is large.

The second weird idea

The second idea is to flatten the array without looking at it or traversing it. It sounds a little strange, how can you shoot flat without traversing? Just use the join() method to convert the array into a string, then remove the regular symbols and finally merge. When using this method, be careful not to join(""), because if divided like this, is 13 1 and 3 or 13? It’s hard to distinguish, the code is as follows:

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

Note: This method will convert the data type into a string.

Array deduplication

The following is array deduplication. For example, [1,2,3,3,4,5,5,5,6] becomes [1,2 ,3,4,5,6]. The core of this implementation is to remove duplicates. The key is to be able to quickly determine whether elements are repeated.

There are still two ideas

The first traversal idea

is to prepare a new array variable, and traverse this variable each time to see if there is any If there are no duplicates, insert them. The new array generated is the array after deduplication. 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;
}
Copy after login

The second method using hash judgment

The time complexity of the above method is O(n^2) It is not a good method. Its bottleneck is to determine whether it is repeated, so we switch to a more efficient method of retrieving whether it is repeated. This method is hashing. Why is hash retrieval the fastest? Let’s look through the data structure, I won’t go into details here.

The idea of ​​this method is to add a hash filter between the original array and the deduplicated array. Generally speaking, the original array data is handed over to the hash to see if there are duplicates. If not, add them. The specific code is as follows:

function uniqueArr(arr){
 var newArr = [],
 hashFilter = {};
 for(var i = 0;i<arr.length;i++){
 if(!hashFilter[arr[i]]){
 //若不存在将此属性对应的值改为true,并塞入去重数组中
 hashFilter[arr[i]] = true;
 newArr.push(arr[i]);
 }
 }
 return newArr;
}
Copy after login

I prefer the second type, because it is really fast to judge whether to repeat it, it can be said to be done in seconds.

Summary

The above is the entire content of this article. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, you can leave a message to communicate.

For more examples of methods of deduplicating and flattening arrays in Javascript, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles