Array-heavy operations are often used in JavaScript project development. This is the way to use the JS array to heavy.
Demo1:
The first: JS array de-re-operation method is to use the traversal of the original array, using the array of indexof () method to determine whether the new array B has the original array of elements in a, if not, after the B array followed by the a[i], if there is no action, and finally can achieve the operation of the array to redo.
This method should be the usual development of the most commonly used JS array to the method of heavy, simple and practical.
Demo2:
The second method of de-weight is more ingenious, is to define an empty object and an empty array, when traversing the original array to use the original array A's element value as a property to define the empty object C, and then determine if c[a[i]] does not exist, then define the property of the object C C[a[i]] The property value is 1 (can be anything). At this point to understand a lot, and so on, and so on when the property name of the next occurrence and C[a[i]] is the same as the original array A when the elements of a repetition of the result is true this time out of judgment, the new array B does not append this element value, and then can achieve the effect of the array deduplication, the demo is clear, can refer to.
DEMO3:
The third way of JS array de-weight is to use JS's foreach method to traverse the original array A, and then use the formal parameter val,index,array to make the judgment. Array.indexof (Val) ==index. The use of the array's indexof () in the If judgment determines whether the returned result is the first occurrence of the value in parentheses, and if true in the parentheses indicates that the current Val value is the first occurrence in the array, so the value is appended to the empty array B, which in this case, all subsequent This value will be returned to false, do not do any processing, so you can achieve the effect of the array de-weight, this method using foreach is more ingenious, also recommended to use.
Demo4:
The fourth kind of array de-weight method is also more common, first the original array a from small to large or from large to small sort, and then define an empty array B, and define a variable item. Iterate over the original array A, judging item! in the For loop =a[i], if not equal then B append this a[i], and item equals A[i]. If they are equal, they are skipped, which also allows the operation of the array to be repeated.
Of course, the method of array de-weight in javascript more than these four, there must be other good ways to go to the weight, if there is a good way to add to me.
Make a little progress every day
JavaScript array de-weight method