what I want to get is like clean([3,2,3,2,5,1]) == [5,1], for learning purpose, I want to do it using recursive function and vanilla javascript only. The function I wrote is as follows:
r=[];
var clean = function(array){
var s1=array.slice(0);
var s2=array.slice(0);
if(s2[0] !== undefined) {
r.push(s2.shift());
for (i=0,flag=false;i<s2.length;i++){
if (r[r.length-1] == s2[i]){
s1[i+1]=undefined;
flag=true;
}
}
if (flag==true){
r.pop();
s1.shift();
for (j=0;j<s1.length;j++){
if (s1[j] == undefined) {s1.splice(j,1);j--};
}
}
else{
s1.shift();
}
}
if (s2.length !== 0) clean(s1);
return;
}
It seems working, but there are something I don't feel comfortable with:
First of all, I'm very new to programming, when I write javascript functions, I always feel the need to define a variable outside the function to store the result, as r in this case, I know this is a very bad practice and I should define a variable inside the function and just return it. But I spent 6 hours on writing above codes(don't laugh at me), now my brain is totally failing me, I can't think of a way to bring this variable into the function. Any hints are greatly appreciated;
Secondly, when I loop through an array and modify it, its length changes on the go, making the loop unreliable, I had to copy the array to 2 different variables(s1,s2) to avoid looping problem. This is very awkward. Later I think of that I can modify the looping index on the go while the array length changes (as you can see in the j loop), but is this a good practice? The following improved function seems working too:
var ccc = function(array){
var s1=array.slice(0);
if(s1[0] !== undefined) {
r.push(s1.shift());
for (i=0,flag=false;i<s1.length;i++){
if (r[r.length-1] == s1[i]){
s1.splice(i,1);
i--;
flag=true;
}
}
if (flag==true){
r.pop();
}
if (s1.length !== 0) ccc(s1);
}
return;
}
Besides, I know jQuery probably has a function to achieve this, but if no frame is allowed, what is the best approach(recursive or not)? I briefly search around stackoverflow but find no exact answers.
0. If it is already a property, set its value to1. Then iterate through the keys of the object and build a result array from the keys whose value is0.jvariable. If you meantiandi--, then that's a common way to deal with that problem.