Basic algorithmFor instance we have an object array:
[10, 1, 1, 2, 1, 2]. Then we want to remove all the same occurrences to be just
[10, 1, 2]without changing the original sequence.
- About the comparing (pairing), it uses combinatoric pattern.
If you have 3 fruits and you wanna compare each of them, then you'll need 3 steps.
If you have five fingers, then you'll need 10 steps to compare them all.
That's the basic idea.
In this "translation", for instance that 3 fruits example, I created object of pairs. But not actually creating an object, just imaginary.
fruit 1 compared to fruit 1, fruit 2, and fruit 3.As you can see, there are repetitions.
fruit 2 compared to fruit 1, fruit 2, and fruit 3.
fruit 3 compared to fruit 1, fruit 2, and fruit 3.
Without conditional statement, it will compare to itself and everything'll be broken.
You can read about that below, about the
- About the array manipulation, I use
splice(index, how_many, elm_1, ..., elm_n)method to remove the element.
And to keep the first element (the comparison reference) intact and only the next occurrence gets deleted, I put less than operator. The first index (denoted by
min the script below) is the array element reference, and the next one (denoted by
n) is the other element besides that reference element.
- The array reconstruction has stages, so I put "flag" to indicate whether it should re-invoke itself or not. The "stages" occur because whenever an array element gets deleted, the length of the array will change, thus the index shifting.
- This function won't change the original array because it uses
slice()method to clone it first.
Updated April 19, 2015
var filtered_array = r_d(your_original_array);
The shorter version at GitHubIn that shorter version, instead of completely deleting the array element, I substitute it with
"array_element (*)"string. You can put other type of dummy element so that it won't mix with the actual array elements.
Different version at GitHubIn this version, I use the actual
Objectdilly. It's one line shorter than the shortened version of the 1st snippet.
This object construction method will return the sorted array. So you probably do not want to use this version.
But if... Hm.
That is all.