Web Front-end
JS Tutorial
Detailed examples of several ideas for deduplication of JavaScript arraysDetailed examples of several ideas for deduplication of JavaScript arrays
The demand for data deduplication is actually that tool libraries such as lodash have mature and complete implementations and can be maturely used in production environments. But this does not prevent us from the perspective of thinking expansion to see how duplication removal can be achieved using several ideas. This article mainly shares with you several ideas for deduplication of JavaScript arrays.
The first is the implementation of the conventional double-layer circular comparison idea
function doubleLoopUniq(arr) {
let result = [];
for (let i = 0, len = arr.length, isExist; i <p>Use the built-in indexOf of js to remove duplicates</p><pre class="brush:php;toolbar:false">function indexOfUniq(arr) {
let result = [];
for (let i = 0, len = arr.length; i <p>After sorting, compare before and after to remove duplicates</p> <pre class="brush:php;toolbar:false">function sortUniq(arr) {
let result = [], last;
// 这里解构是为了不对原数组产生副作用
[ ...arr ].sort().forEach(item => {
if (item != last) {
result.push(item);
last = item;
}
});
return result;
}Deduplication through hashTable
function hashUniq(arr) {
let hashTable = arr.reduce((result, curr, index, array) => {
result[curr] = true;
return result;
}, {})
return Object.keys(hashTable).map(item => parseInt(item, 10));
}ES6 SET one line of code to achieve deduplication
function toSetUniq(arr) {
return Array.from(new Set(arr));
}splice deduplication (directly operates the array itself, with side effects)
function inPlaceUniq(arr) {
let idx = 0;
while (idx <p>Finally in Run a simple test under nodejs to see which one is more efficient~</p><pre class="brush:php;toolbar:false">let data = [];
for (var i = 0; i <p>The results are as follows</p><pre class="brush:php;toolbar:false">hashTable 168ms
sortUniq 332ms
toSetUniq 80ms
indexOfUniq 4280ms
doubleLoopUniq 13303ms
inPlaceUniq 9977msExtended thinking: If the elements in the array are objects, how to remove duplicates?
Since it is a reference type, deepEqual will inevitably be used. Although this idea can answer this problem, it is inevitably not efficient enough.
It can also be seen from the above test that deduplication through new Set and hashTable is the most efficient.
So there is no doubt that we need to transform based on these two methods. I want to use hashTable.
On the other hand, in order to reduce the time-consuming caused by deep comparison, I try to use JSON.stringify to reference The type is converted to a basic type.
function collectionUniq(collection) {
let hashTable = {};
collection.forEach(item => {
hashTable[JSON.stringify(item)] = true;
})
return Object.keys(hashTable).map(item => JSON.parse(item))
}Then here comes the problem. We all know that the attributes of objects are unordered. If the data is like this, then it is GG.
let collection = [ { a: 1, b: 2, c: 3 }, { b: 2, c: 3, a: 1 } ]There is a toHash idea, After a basic deduplication of this array, in order to ensure accuracy,
first traverse the JSON string=>
Pass charCodeAt() gets the unicode encoding of each string =>
and adds them to get a total number. Finally, compare them in pairs. Those with equal values are duplicates, thus achieving the effect of deduplication.
function toHash(obj) {
let power = 1;
let res = 0;
const string = JSON.stringify(obj, null, 2);
for (let i = 0, l = string.length; i <p>This is just a basic idea for implementation, and there is a lot of room for improvement. In order to reduce the possibility of hash collision, the weight of some special characters can be increased or decreased. </p><p><strong>The key point is to ensure that the probability of collision is smaller than winning the jackpot. </strong></p><p class="comments-box-content">Related recommendations: <br></p><p class="comments-box-content"><a href="//m.sbmmt.com/js-tutorial-386521.html" target="_self"> Sharing several methods of deduplication in JavaScript arrays</a></p><p class="comments-box-content"><a href="//m.sbmmt.com/php-weizijiaocheng-386230.html" target="_self"> Implementing array deduplication in PHP Method code</a></p><p class="comments-box-content"><a href="//m.sbmmt.com/js-tutorial-384672.html" target="_self">JS simple implementation of array deduplication method analysis</a></p>The above is the detailed content of Detailed examples of several ideas for deduplication of JavaScript arrays. For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.
The Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AMThe latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

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

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function





