Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Function that returns all indexes that do not overlap - Javascript

I have an array like so:

[
    {
        indexes: [1, 3, 5, 8],
        length: 2
    }, 
    {
        indexes: [2, 4, 6, 7],
        length: 1
    }
]

I am using this to split a string (and many other similar ones):

matatatatt

I am trying to split it by the array ['at', 't'], which should return something like this in the future:

['m', 'at', 'at', 'at', 'at', 't']

This is the code I currently have:

function splitVars (eq, vars) {
        let splitted = eq.split("");
        let locs = [];

        for (let i = 0; i < vars.length; i++) {
            let variable = vars[i];

            let found = locations(variable, eq)

            locs.push({
                indexes: found,
                variable: variable,
                varLength: variable.length
            })
        }

        return locs;
    }

    function locations(substring, string){
        var a=[],
            i=-1;
        while((i = string.indexOf(substring, i + 1)) >= 0) a.push(i);
        return a;
    }        

console.log(splitVars('wmtmtmtt', ['mt', 't']));

However, back to my question. As you can tell, because the length of the second string is one, it is picking up the one letter in the first indexes that is the same. Because the indexes [2, 4, 6] are overlapping with the first indexes, I would like to remove them.

How can I do such a thing?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!