I have 2 arrays
IDList ["01","02","03","04"]
Which contains some ID’s of something.
And i have an another list of ID who tells which element of IDList possess the flag example
IDLISTPRD["01","02","03","04"]
As you see here all elements of IDList possess the flag according to IDLISTPRD
I want to check if any of this ID has 3 flags in a row.
I have made this code
let eqObj = {};
for (var i = 0; i < IDLISTPRD.length; i++) {
if (IDList.includes(IDLISTPRD[i])) {
eqObj[IDLISTPRD[i]] = IDList.indexOf(IDLISTPRD[i]);
}
}
First i am pushing elements(ID’s) that are the same (possess the flag)
According to 2 arrays this will return eqObj [ ["01" : 0,"02" : 1,"03" : 2,"04" : 3]]
In order to compare them i will have to sort them
let objSorted = Object.entries(eqObj ).sort(function (a, b) {
return b[1] - a[1];
});
let flagInRow= 0;
let flagInRowIndicator= true;
for (var i = 0; i < objSorted .length - 1; i++) {
if (objSorted [i][1] - objSorted [i + 1][1] == 1) {
flagInRow++;
} else {
flagInRow= 0;
}
if (flagInRow< 2) {
flagInRowIndicator= true;
} else {
flagInRowIndicator= false;
break;
}
}
As you can see here the flaginRowIndicator turn true when it finds 3 flags in a row
now i am trying to keep the logic but to remove the middle element of the array
example
if i have the array with
["1","2","3"]
where three of this have flags i want to remove the middle one and to return an array with only ["1,"3"]
Another example if it would have 6 flags in a row ["1","2","3","4","5","6"]
I want to remove only the middle ones of 3 rows like in this case to remove 2 and 5 and to return
["1","3","4","6"]
>Solution :
You could iterate from the end and splice the array.
function removeMiddle(array) {
let i = array.length - 2;
while (i > 0) {
array.splice(i, 1);
i -= 3;
}
return array;
}
console.log(removeMiddle([1, 2, 3]));
console.log(removeMiddle([1, 2, 3, 4, 5, 6]));