How to deduplicate Javascript array
This article mainly introduces how to duplicate the Javascript array, the article introduces in great detail, has a certain reference value, interested friends must read it!
Array deduplicated 1 double-layer for loop (similar to bubble sorting) var arr = [2 var I = 0 I {if (! arr2.includes (e)) {arr2.push (e)}) console.log (arr2) / / arr2: [1,2 arr2.includes (e)}) console.log (arr2) / / arr2: [1,2 arr2.includes (e)) 3 console.log (arr2) / / arr2: [1, 2, 2, 3, 21, 34] 3 can't repeat weight by using object attributes. Var arr2=Object.keys (obj) console.log (arr2) / / arr2: ["1", "2", "3", "4", "12", "21", "34"] var arr3 = arr2.map (e = > ~ e) / / arr3: [1, 2, 3, 4, 12, 21, 34] / Note that this method not only rearranges the array, but also changes the type of elements in the array.
~ is the bitwise inverse operator in js. ~ ~ is to perform bitwise inversion twice, in fact, to keep the original value, but note that although it is the original value, performing this operation on a Boolean variable will be converted into a corresponding numerical variable, that is, ~ true = = 1.
4 ES6 Set
ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values.
Var arr = [2, new Set (arr)] console.log (arr1) / / arr1: [1, 2, 3, 21, 34] 5 ES6 Array. Prototype.filter ()
Note: when indexOf looks for an element in an array, it will return its subscript when it encounters the first one that meets the criteria.
Var arr = [2beacon 3jorie 4jiggle 21jiggle 12Power3jiguo 4jiguo 1] var arr2 = arr.filter ((ePoweri) = > {/ / see if the first subscript position of the elements of each cycle (the position returned by indexOf) is consistent with the subscript of the elements of each cycle (I of each filter loop), which means that he is the first one who meets the criteria and will not be filtered out. Return arr.indexOf (e) = = I;}) console.log (arr2) / / arr2: [1,2,3,4,12,21,34] 6 ES6 Array. Prototype.reduce () var arr = [2, pre,e, 3, 4, 4, 21, 1, 12, 3, 4, 1] var arr2 = arr.reduce ((pre,e) = > {/ / here, of course, indexOf can also be used to determine whether there is pre.includes (e)? pre:pre.push (e) Return pre}, []) console.log (arr2) / / arr2: [1, 2, 3, 4, 12, 21, 34] these are all the contents of the article "how to repeat the Javascript array". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!