writing a function that return a list without any elements that are the same nex
ID: 3821455 • Letter: W
Question
writing a function that return a list without any elements that are the same next to each other, maintaining the original order. having some issues getting work correctly, here's what i have so far, I prefer the function use two counters.
var order = function(iterable) {
var freq = [ ];
var count = 1;
for(var i = 0; i < iterable.length; i++) {
count = 1;
}
for(var j = i+1; j < iterable.length; j++) {
if(iterable[i] == iterable[j]) {
count++;
}
else { freq.push(iterable[j]);
}
return freq;
}
}
order([A,A,a,B,B,c, A, D, D]); (should output: [A,a,B,c,a,D])
Explanation / Answer
This will simply do the needful:
var order = function(iterable) {
var newList = [];
var j = 0;
for(var i = 0; i < iterable.length-1; i++)
{
if(iterable[i] != iterable[i+1]) //If the side by side elements are not the same.
newList[j++] = iterable[i]; //add them to output.
}
newList[j] = iterable[iterable.length-1]; //Add the last element.
return newList;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.