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

What are the methods of array deduplication in JavaScript

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you what are the methods to achieve array de-duplication in JavaScript. I hope you will get something after reading this article. Let's discuss it together.

Array deduplication const arr = [1, 1,'1, 17, true, true, false, false, 'true',' a circle, {}, {}]; / / > [1,'1, 17, true, false, 'true',' a weight, {}, {}] method 1: using Setconst res1 = Array.from (new Set (arr)); method 2: two-layer for loop + spliceconst unique1 = arr = > {let len = arr.length; for (let I = 0) I

< len; i++) { for (let j = i + 1; j < len; j++) { if (arr[i] === arr[j]) { arr.splice(j, 1); // 每删除一个树,j--保证j的值经过自加后不变。同时,len--,减少循环次数提升性能 len--; j--; } } } return arr;}方法三:利用indexOfconst unique2 = arr =>

{const res = []; for (let I = 0; I

< arr.length; i++) { if (res.indexOf(arr[i]) === -1) res.push(arr[i]); } return res;}方法四:利用includeconst unique3 = arr =>

{const res = []; for (let I = 0; I

< arr.length; i++) { if (!res.includes(arr[i])) res.push(arr[i]); } return res;}方法五:利用filterconst unique4 = arr =>

{return arr.filter ((item, index) = > {return arr.indexOf (item) = index;});} method 6: use Mapconst unique5 = arr = > {const map = new Map (); const res = []; for (let I = 0; I < arr.length; iTunes +) {if (! map.has (arr [I])) {map.set (arr [I], true) res.push (ARR [I]);} return res } after reading this article, I believe you have a certain understanding of "what are the methods to achieve array de-duplication in JavaScript". If you want to know more about it, welcome to follow the industry information channel, thank you for reading!

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