Home > Web Front-end > JS Tutorial > Analysis of JS simple method to implement array deduplication

Analysis of JS simple method to implement array deduplication

韦小宝
Release: 2018-01-12 09:53:32
Original
1543 people have browsed it

This article mainly introduces the method of JS to simply implement array deduplication. It analyzes js array traversal and judgment related operation skills and precautions based on specific examples. If you are interested in JS Friends can refer to this article

The example in this article describes the simple method of deduplicating arrays in JS. Share it with everyone for your reference, the details are as follows:

var arr = ['abc','abcd','sss','2','d','t','2','ss','f','22','d'];
//定义一个新的数组
var s = [];
//遍历数组
for(var i = 0;i<arr.length;i++){
  if(s.indexOf(arr[i]) == -1){ //判断在s数组中是否存在,不存在则push到s数组中
    s.push(arr[i]);
  }
}
console.log(s);
//输出结果:["abc", "abcd", "sss", "2", "d", "t", "ss", "f", "22"]
Copy after login


Running results:

About indexOf( ) method:

indexOf() method returns the position where a specified string value first appears in the string.

<a href="//m.sbmmt.com/wiki/57.html" target="_blank">string</a><a href="//m.sbmmt.com/wiki/60.html" target="_blank">Object</a>.indexOf(searchvalue,fromindex)

This method will retrieve the string stringObject from beginning to end , to see if it contains the substring searchvalue. The starting position of the search is at the fromindex of the string or the beginning of the string (when fromindex is not specified). If a searchvalue is found, the position of the first occurrence of searchvalue is returned. Character positions in stringObject start from 0.

If the string is not found in the array, -1 is returned.

About the push() method:

push() The method can add one or more elements to the end of the array and return a new length.

Note: New elements will be added at the end of the array.

Note: This method changes the length of the array.

Related recommendations:

Detailed examples of several precautions for JS to jump to the mobile site URL

Detailed examples of JS function throttling and anti-shake

JS simple implementation of sliding loading data instance sharing

The above is the detailed content of Analysis of JS simple method to implement array deduplication. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template