s.purpose s.purpose - 6 months ago 8
Javascript Question

Remove triplet items from array

I do want to remove the numbers that appears (03) times from my array. I don't want to remove duplicates because it will still leave the numbers I don't want. The repetitive numbers are 143 & 187.

var number = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 143, 143, 143, 149, 151, 157, 163, 167, 173, 179, 181, 187, 187, 187, 191];
for (i = 0; i < number.length; i++) {
if ((number[i] == number[i + 1]) && (number[i + 1] == number[i + 2])) {
document.write(number[i]);
document.write(number[i + 1]);
document.write(number[i + 2] + "<br>");
number.splice(number[i - 1], number[i], number[i + 1], number[i + 2]);
}
};
document.write(number);

Answer

I tried it like the following. You can remove 3 or more consecutive occurrences using the following.

var number = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 143, 143, 143, 143, 149, 151, 157, 163, 167, 173, 179, 181, 187, 187, 187, 191];
var prev;
var occurance = 1;
var deletePos = [];
var offset = 0;
/* Get 3+ repeat positions. */
for(i = 0; i < number.length; i++){
  if(occurance >= 3 && prev != number[i])
    deletePos.push({occurance: occurance, index:i});
  occurance = (prev == number[i]) ? (occurance + 1) : 1;
  prev = number[i];
}
/* Delete items in each positions. */
for(j = 0; j < deletePos.length; j++){
  var reObj = deletePos[j];
  number.splice((reObj.index - offset - reObj.occurance), reObj.occurance);
  offset += reObj.occurance;
}
document.write(number);