Home >Web Front-end >JS Tutorial >Detailed explanation of how to remove duplicate elements from array in JS
This article mainly introduces the method of removing repeated elements in array in JS. Friends who need it can refer to
I read Liao Xuefeng’s## today. #js tutorial, I saw the usage of filter.
The method used to remove duplicate elements in Array is recorded here.Filter
Filter is a commonly used operation. It is used to filter out certain elements of Array and then return the remaining elements. Similar tomap(), Array's filter() also receives a function. Unlike map(), filter() applies the passed function to each element in turn, and then decides to retain or discard the element based on whether the return value is true or false.
Using filter, you can cleverly remove the repeated elements of Array:'use strict'; var r, arr = ['apple', 'strawberry', 'banana', 'pear', 'apple', 'orange', 'orange', 'strawberry']; r = arr.filter(function (element, index, self) { return self.indexOf(element) === index; });Because indexOf in Array always returns the position where an element appears for the first time, the position of subsequent repeated elements is the same as indexOf The returned positions are not equal, so they are filtered out by the filter.
The above is the detailed content of Detailed explanation of how to remove duplicate elements from array in JS. For more information, please follow other related articles on the PHP Chinese website!