Directory
- 1. Double-layer loop (violent method)
- 2. indexOf and includes
- 3. Sorting and deduplication
- 4. Filter
- 5. Key-value pair(key-value)
- 6.ES6
- 7 , some questions
- Reference
Write at the end
(Related free learning recommendations: javascript video tutorial)
1. Double-layer circulation
const unique = (arr)=>{ for(let i = 0; i { var arr = [1, '1', '1', 1, 2, true, false, true, 3, 2, 2, 1]; var newArr = []; for(let i = 0; i <p><strong>Core point:</strong></p>
- Time complexity:
O(n^2)
- The above two methods are two loop traversals, and the processing methods are slightly different
- The above implementation methods are indeed It’s not the best choice, but it has good compatibility~
2. indexOf and includes
2.1 indexOf simplifies one-level loop judgment
Core point:
- If you need to return the original array, you can find the duplicate item in the
indexOf
method (not equal to the position where it first appeared ) when usingsplice
to remove -
indexOf
: Returns thefirst index
where a given element can be found in the array, if not If exists, -1 is returned. -
indexOf(ele, fromIndex)
- ele: The element to be found
- fromIndex: The starting position of the element to be found, the default is 0, negative numbers are allowed, -2 means starting from the second to last element
- Return a subscript (number)
##Code:
const unique = (arr) => { var res = []; for (let i = 0; i 2.2 includesSimplify one layer of loop judgment<h5></h5><p>Core point:<strong></strong></p>
- You can combine it by yourself whether you want to return the original array or a new array~
- includes
: Used Determine whether an array contains a specified value. Depending on the situation, if it does, it will return
true, otherwise it will return
false ##includes(ele, fromIndex) -
ele: The element to be found
- fromIndex: Start searching at the specified index. The default is 0. If it is a negative value, jump forward by the absolute value of fromIndex
- indexes from the end. .
Return result (bool)
const unique = (arr) => {
var res = [];
for (let i = 0; i
2.3 indexOf and includes selection for the current scene
Here we recommend using includes to find elements:
The return value can be directly used as the conditional statement of if, conciseif(res.indexOf(arr[i]) !== -1 ){ todo }// orif(res.includes(arr[i])){ todo }
NaNIf there is
in the array, and you just need to determine whether the array exists NaN
, then you use indexOf
cannot be judged, you must use the includes
method. <pre class="brush:php;toolbar:false">var arr = [NaN, NaN];arr.indexOf(NaN); // -1arr.includes(NaN); // true</pre>
undefinedIf there is an
value in the array, includes
will think The empty value is undefined
, but indexOf will not. <pre class="brush:php;toolbar:false">var arr = new Array(3);console.log(arr.indexOf(undefined)); //-1console.log(arr.includes(undefined)) //true</pre>
Core point:
After the array is sorted, the same elements will Adjacent, so if the current element is different from its adjacent elements, it is stored in a new array;
- Compared with indexOf, only one loop is needed;
- concat will splice the arrays , and returns a new array;
- sort() sorting is done by sorting according to the Unicode position of each character of the converted
- string. So it is difficult to guarantee its accuracy;
var arr = [1, 1, '1'];function unique(arr) {
var res = [];
var sortedArr = arr.concat().sort();
var last;
for (var i = 0; i
Core point:
filter: method creates a new array containing all elements of the test
- implemented by the provided
- function (returns the elements for which the test function is established)
- :
callback accepts three parameters: element-the element currently being processed, index-the current element index, array-the filter was called The array itself
- thisArg: The value used for this when executing callback. Using filter we can simplify the outer loop at the code level:
var arr = [1, 2, 1, 1, '1'];const unique = function (arr) {
var res = arr.filter(function(item, index, arr){
return arr.indexOf(item) === index;
})
return res;}console.log(unique(arr)); // [ 1, 2, '1' ]
Combined sorting ideas :
var arr = [1, 2, 1, 1, '1'];const unique = function (arr) { return arr.concat().sort().filter(function(item, index, arr){ return !index || item !== arr[index - 1] })}console.log(unique(arr));5. Key-value pair
The methods mentioned above can be roughly divided into
Non-sorted array, two traversal judgments (traversal, query)- Sorted array, comparison of adjacent elements
- We propose another way, using the key-value of the Object object Method, to count the number of elements appearing in the array, there are two preliminary judgment logics
Take
[1,1,1,2,2,3,'3']for example: <ol>
<li>统计每个元素出现的次数,obj:{1: 3, 2: 2, 3: 3}, 返回这个<code>obj
的key
而不管他们的value
5.1 统计次数
var arr = [1, 2, 1, 1, '1', 3, 3];const unique = function(arr) { var obj = {}; var res = []; arr.forEach(item => { if (!obj[item]) { obj[item] = true; res.push(item); } }); return res;}console.log(unique(arr)); // [1, 2, 3]
5.2 结合filter
var arr = [1, 2, 1, 1, '1'];const unique = function(arr) { var obj = {}; return arr.filter(function(item, index, arr){ return obj.hasOwnProperty(item) ? false : (obj[item] = true) })}console.log(unique(arr)); // [1, 2]
5.3 key: value存在的问题
对象的属性是字符串类型的,即本身数字1
和字符串‘1’
是不同的,但保存到对象中时会发生隐式类型转换,导致去重存在一定的隐患。
考虑到string和number的区别(typeof 1 === ‘number’, typeof ‘1’ === ‘string’),
所以我们可以使用 typeof item + item
拼成字符串作为 key 值来避免这个问题:
var arr = [1, 2, 1, 1, '1', 3, 3, '2'];const unique = function(arr) { var obj = {}; var res = []; arr.forEach(item => { if (!obj[typeof item + item]) { obj[typeof item + item] = true; res.push(item); } }); return res;}console.log(unique(arr)); // [ 1, 2, '1', 3, '2' ]
六、ES6
随着 ES6 的到来,去重的方法又有了进展,比如我们可以使用 Set 和 Map 数据结构。
6.1 Set
Set:它允许你存储任何类型的唯一值,无论是原始值或者是对象引用
代码:
var arr = [1, 2, 1, '1', '2'];const unique = function(arr) { return Array.from(new Set(arr));}console.log(unique(arr)); // [ 1, 2, '1', '2' ]
简化1:
function unique(array) { return [...new Set(array)];}
简化2:
var unique = (a) => [...new Set(a)]
6.2 Map
Map 对象保存键值对,并且能够记住键的原始插入顺序。任何值(对象或者原始值) 都可以作为一个键或一个值。
- Map.prototype.has(key):返回一个布尔值,表示Map实例是否包含键对应的值。
- Map.prototype.set(key, value):设置Map对象中键的值。返回该Map对象。
function unique (arr) { const newMap = new Map() return arr.filter((a) => !newMap.has(a) && newMap.set(a, 1));}
写到这里比较常规的数组去重方法就总结的差不多了,如果需要更强大的去重方法,我们需要对他们进行组合,而且因为场景的不同,我们所实现的方法并不一定能涵盖到
相关免费学习推荐:javascript(视频)
The above is the detailed content of JavaScript Topic 2: Array Deduplication. For more information, please follow other related articles on the PHP Chinese website!

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Zend Studio 13.0.1
Powerful PHP integrated development environment
