I have two arrays - grid and pattern
const G = [
[9,9,9,9,9,9]
]
const P = [
[9,9]
]
I want to get every occurrence of P within G. So the output would be something like this:
[
{
line: 0,
charAtStart: 0,
charAtEnd: 2,
},
{
line: 0,
charAtStart: 2,
charAtEnd: 4,
},
{
line: 0,
charAtStart: 4,
charAtEnd: 6,
},
{
line: 0,
charAtStart: 6,
charAtEnd: 8,
},
{
line: 0,
charAtStart: 8,
charAtEnd: 10,
}
]
What I've done so far:
for(let i = 0, l = G.length; i < l; i++) {
if(G[i].toString().includes(P[0].toString())) {
console.log(G[i].toString(), '\n',
P[0].toString(), '\n',
G[i].toString().indexOf(P[0].toString())
)
availableFirstLines.push({
line: i,
charAtStringStart: G[i].toString().indexOf(P[0].toString()),
charAtStringEnd: (G[i].toString().indexOf(P[0].toString())) + P[0].toString().length - 1
})
}
}
So I loop through G. First of all I check if P even exists within G[0]. If so I push its indexOf first char and last char. So my output is
[
{
line: 0,
charAtStart: 0,
charAtEnd: 2,
}
]
problem is that it does detect only first occurrence and then move on. Should I have nested loop to get every occurrence?
Edit I accidentally provided wrong output. I've changed it.
,are also counted. Notice that property ofavailableFirstLinesin code ischarAtStringStart. I probably should called it same in input & output.