I have an array like var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
I really want the output to be [5,2,9,4,5]
. My logic for this was:
- Go through all the element one by one.
- If the element is the same as the prev element, count the element and do something like
newA = arr.slice(i, count)
- New array should be filled with just identical elements.
- For my example input, the first 3 elements are identical so
newA
will be likearr.slice(0, 3)
andnewB
will bearr.slice(3,5)
and so on.
I tried to turn this into the following code:
function identical(array){
var count = 0;
for(var i = 0; i < array.length -1; i++){
if(array[i] == array[i + 1]){
count++;
// temp = array.slice(i)
}else{
count == 0;
}
}
console.log(count);
}
identical(arr);
I am having problems figuring out how to output an element that represents a group of element that are identical in an array. If the element isn't identical it should be outputted in the order that it is in in the original array.