Home  >  Article  >  Web Front-end  >  How to simply deduplicate an array

How to simply deduplicate an array

一个新手
一个新手Original
2017-09-18 10:12:251357browse

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"]

About the indexOf() method:

indexOf() method can return a specified string value The position of the first occurrence in the string.

stringObject.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:

The push() method can add an element to the end of the array or multiple elements and returns the new length.

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

#Note: This method changes the length of the array.

The above is the detailed content of How to simply deduplicate an array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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