Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the deduplication of javascript array

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "javascript array de-duplication how to achieve", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "javascript array de-duplication how to achieve" this article.

Methods: 1, use "[... new Set (arr)]" statement; 2, use "Array.from (new Set (arr))" statement; 3, use filter and indexOf function; 4, use double for loop to check whether the value is duplicated, if there is a repetition, use push () to delete.

The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.

Method 1: [… New Set (arr)]

Const arr = [1, 2, 3, 2, 3]; [... new Set (arr)]; / / [1,2,3]

Method 2:Array.from (new Set (arr))

Const arr = [1,2,3,2,3]; Array.from (new Set (arr)); / / [1,2,3]

Because elements in Set are unique, whether they are original values or object references, you can de-duplicate by converting an array to a Set object

The Array.from method converts a Set object into an array.

Method 3: using filter+ indexOf

Function unique (arr) {return arr.filter (function (item, index, arr) {/ / current element, first index in the original array = = current index value, otherwise return current element return arr.indexOf (item, 0) = index;}) } var arr = [1 unique (arr)) / / [1, true, true,15, false, undefined, null, NaN ", 0," a ", {… }, {... }]

Method 4: double for cycle

The easiest way to understand is to loop through elements in the outer layer and check for repetition in the inner loop.

When there are duplicate values, you can use either push () or splice ()

Function distinct (a, b) {let arr = a.concat (b); for (let item0, len=arr.length; I)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report