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!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version
