Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the methods of array deduplication in JavaScript

Shulou Source: shulou.com Published: 2022-06-01 03:45:36 10月05日 Update

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!

Tags: Methods arrays real articles loops at the same time finished performance more times knowledge industry information channels channels jackers guarantee Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux NVidia Shulou Tech Info MySQL Huawei