Home > Web Front-end > JS Tutorial > body text

Array deduplication in JavaScript and Python

小云云
Release: 2018-02-23 14:11:52
Original
1845 people have browsed it

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

Python array deduplication

>>> 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]
Copy after login

JavaScript array deduplication

<!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>
Copy after login

Array deduplication in JavaScript and Python

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!

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