Home Web Front-end JS Tutorial How to implement array deduplication algorithm in JS

How to implement array deduplication algorithm in JS

May 23, 2018 am 11:46 AM
javascript array algorithm

This time I will show you how to implement the array deduplication algorithm in JS. What are the precautions for implementing the array deduplication algorithm in JS? The following is a practical case, let's take a look.

Test case:

arr = ["1",3,"1",1,4,5,1,"2",5,1,{"name ":"li","age":20},2,4,3,{"name":"li","age":20},""];

Method 1: With the help of temporary array and indexOf, The algorithm complexity is: O(n^2)

function unique1(arr){
  var temp = [];
  for(var i=0; i<arr.length; i++){
    if(temp.indexOf(arr[i]) == -1){
      temp.push(arr[i]);
    }
  }
  return temp;
}
Test result:

unique1(arr): ["1", 3, 1, 4, 5, "2", Object { name="li", age=20}, 2, Object { name="li", age=20}, ""]

bug Unable to distinguish objects

Method 2: Use Object object in JavaScript as Ha Greek table

function unique2(arr){
  var temp=[];
  var hash={};
  for(var i=0; i<arr.length;i++){
    if(!hash[arr[i]]){
      hash[arr[i]]=true;
      temp.push(arr[i]);
    }
  }
  return temp;
}
Test result:

unique2(arr): ["1", 3, 4, 5, "2", Object { name="li ", age=20}, ""]

bug: Unable to distinguish: 1 and "1"

Modification

function unique2(arr){
  var temp=[];
  var hash={};
  for(var i=0; i<arr.length;i++){
      var item = arr[i];
    var key = typeof(item)+item;
    if(!hash[key]){
      hash[key]=true;
      temp.push(arr[i]);
    }
  }
  return temp;
}
Test result:

unique2(arr): ["1", 3, 1, 4, 5, "2", Object { name="li", age=20}, 2, ""]

Method 3: First use sort to sort the array, and then use a temporary array to store the last one of the same element. This method can only be used for pure Number type arrays

function unique3(arr){
  arr.sort(function(a,b){
    return a-b;
  });
  var temp = [];
  for(var i=0;i<arr.length;i++){
    if(arr[i] !== arr[i+1]){
      temp.push(arr[i]);
    }
  }
  return temp;
}
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to use Vue better-scroll to implement alphabetical index navigation

How to implement Vue WeChat project on demand Authorized login

The above is the detailed content of How to implement array deduplication algorithm in JS. For more information, please follow other related articles on 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

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)

Hot Topics

PHP Tutorial
1504
276
Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Jun 03, 2024 pm 01:25 PM

Common challenges faced by machine learning algorithms in C++ include memory management, multi-threading, performance optimization, and maintainability. Solutions include using smart pointers, modern threading libraries, SIMD instructions and third-party libraries, as well as following coding style guidelines and using automation tools. Practical cases show how to use the Eigen library to implement linear regression algorithms, effectively manage memory and use high-performance matrix operations.

Application of algorithms in the construction of 58 portrait platform Application of algorithms in the construction of 58 portrait platform May 09, 2024 am 09:01 AM

1. Background of the Construction of 58 Portraits Platform First of all, I would like to share with you the background of the construction of the 58 Portrait Platform. 1. The traditional thinking of the traditional profiling platform is no longer enough. Building a user profiling platform relies on data warehouse modeling capabilities to integrate data from multiple business lines to build accurate user portraits; it also requires data mining to understand user behavior, interests and needs, and provide algorithms. side capabilities; finally, it also needs to have data platform capabilities to efficiently store, query and share user profile data and provide profile services. The main difference between a self-built business profiling platform and a middle-office profiling platform is that the self-built profiling platform serves a single business line and can be customized on demand; the mid-office platform serves multiple business lines, has complex modeling, and provides more general capabilities. 2.58 User portraits of the background of Zhongtai portrait construction

Improved detection algorithm: for target detection in high-resolution optical remote sensing images Improved detection algorithm: for target detection in high-resolution optical remote sensing images Jun 06, 2024 pm 12:33 PM

01 Outlook Summary Currently, it is difficult to achieve an appropriate balance between detection efficiency and detection results. We have developed an enhanced YOLOv5 algorithm for target detection in high-resolution optical remote sensing images, using multi-layer feature pyramids, multi-detection head strategies and hybrid attention modules to improve the effect of the target detection network in optical remote sensing images. According to the SIMD data set, the mAP of the new algorithm is 2.2% better than YOLOv5 and 8.48% better than YOLOX, achieving a better balance between detection results and speed. 02 Background & Motivation With the rapid development of remote sensing technology, high-resolution optical remote sensing images have been used to describe many objects on the earth’s surface, including aircraft, cars, buildings, etc. Object detection in the interpretation of remote sensing images

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

The role of PHP array grouping function in finding duplicate elements The role of PHP array grouping function in finding duplicate elements May 05, 2024 am 09:21 AM

PHP's array_group() function can be used to group an array by a specified key to find duplicate elements. This function works through the following steps: Use key_callback to specify the grouping key. Optionally use value_callback to determine grouping values. Count grouped elements and identify duplicates. Therefore, the array_group() function is very useful for finding and processing duplicate elements.

Groundbreaking CVM algorithm solves more than 40 years of counting problems! Computer scientist flips coin to figure out unique word for 'Hamlet' Groundbreaking CVM algorithm solves more than 40 years of counting problems! Computer scientist flips coin to figure out unique word for 'Hamlet' Jun 07, 2024 pm 03:44 PM

Counting sounds simple, but in practice it is very difficult. Imagine you are transported to a pristine rainforest to conduct a wildlife census. Whenever you see an animal, take a photo. Digital cameras only record the total number of animals tracked, but you are interested in the number of unique animals, but there is no statistics. So what's the best way to access this unique animal population? At this point, you must be saying, start counting now and finally compare each new species from the photo to the list. However, this common counting method is sometimes not suitable for information amounts up to billions of entries. Computer scientists from the Indian Statistical Institute, UNL, and the National University of Singapore have proposed a new algorithm - CVM. It can approximate the calculation of different items in a long list.

Can arrays be used as function parameters? Can arrays be used as function parameters? Jun 04, 2024 pm 04:30 PM

Yes, in many programming languages, arrays can be used as function parameters, and the function will perform operations on the data stored in it. For example, the printArray function in C++ can print the elements in an array, while the printArray function in Python can traverse the array and print its elements. Modifications made to the array by these functions are also reflected in the original array in the calling function.

Focus on it! ! Analysis of two major algorithm frameworks for causal inference Focus on it! ! Analysis of two major algorithm frameworks for causal inference Jun 04, 2024 pm 04:45 PM

1. The main tasks of the overall framework can be divided into three categories. The first is the discovery of causal structures, that is, identifying causal relationships between variables from the data. The second is the estimation of causal effects, that is, inferring from the data the degree of influence of one variable on another variable. It should be noted that this impact does not refer to relative nature, but to how the value or distribution of another variable changes when one variable is intervened. The last step is to correct for bias, because in many tasks, various factors may cause the distribution of development samples and application samples to be different. In this case, causal inference may help us correct for bias. These functions are suitable for a variety of scenarios, the most typical of which is decision-making scenarios. Through causal inference, we can understand how different users react to our decision-making behavior. Secondly, in industry

See all articles