Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use indexOf to realize Array de-duplication in JavaScript

Shulou Source: shulou.com Published: 2022-06-01 02:31:53 09月30日 Update

This article is about how JavaScript uses indexOf to remove duplicates in arrays. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Weight removal by indexOf

Function unique (arr) {if (! Array.isArray (arr)) {console.log ('type errorships') Return} var array = []; for (var I = 0; I < arr.length; itemized +) {if (array .indexOf (arr [I]) = =-1) {array. Push (arr [I])} return array;} var arr = [1Jing 1 de truejue de trueju de trueju de truejue, 15 pas falseforme false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0,'a moment,'a moment, {}, {}] Console.log (unique (arr)) / / [1, "true", true, 15, false, undefined, null, NaN, NaN, "NaN", 0, "a", {... }, {... }] / / NaN, {} have not been duplicated

Create an empty result array, for loop the original array, determine whether there is a current element in the result array, skip if it has the same value, and push into the array if it is different.

Thank you for reading! On "JavaScript how to use indexOf to achieve array de-duplication" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, you can share it out for more people to see it!

Tags: Array same content more articles results good practical elements articles read knowledge reference help loops related Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB NVidia Shulou Technology Linux Docker