Home >Web Front-end >JS Tutorial >Analysis of JS simple method to implement array deduplication
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"]
Running results:
About indexOf( ) method:
indexOf()
method returns the position where a specified string value first appears in the string.
<a href="http://www.php.cn/wiki/57.html" target="_blank">string</a><a href="http://www.php.cn/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!