Home > Web Front-end > JS Tutorial > Detailed explanation of how to remove duplicate elements from array in JS

Detailed explanation of how to remove duplicate elements from array in JS

黄舟
Release: 2017-05-26 10:12:38
Original
1451 people have browsed it

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 to

map(), 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;
});
Copy after login

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!

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