"Array deduplication" is a commonly used operation in practical applications, and the probability of appearing in interview questions is also very high. Today I will briefly describe the method of array deduplication in Python and JavaScript. I hope it can help everyone.
>>> a = [9,8,7,9,7,1,2,1,2,5,3] >>> new_a = list(set(a)) >>> new_a [1, 2, 3, 5, 7, 8, 9] #此时new_a未保持原有的顺序,对new_a进行排序 >>> new_a.sort(key = a.index) >>> new_a [9, 8, 7, 1, 2, 5, 3]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript"> var array1 = [1,2,6,8,4,2,3,9,47,1,2,23,5,8,3]; var result = []; for (var i = 0; i < array1.length; i++) { if (array1.indexOf(array1[i])==i) //如过该元素在数组中第一次出现的位置 == 该元素当前的位置【A】 { result.push(array1[i]);//将符合【A】条件的元素加入到result中 } } alert(result); </script> </head> <body> </body> </html>
Related recommendations:
Detailed examples of several ideas for deduplication in JavaScript arrays
Sharing of several methods for deduplication in JavaScript arrays
JS is simple Analysis of methods to achieve array deduplication
The above is the detailed content of Array deduplication in JavaScript and Python. For more information, please follow other related articles on the PHP Chinese website!