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

123
Views
Divide an array into subarray depending on string and join its items. Javascript

I would like to transform an array into another separing its items depending on a string data, and, when there are two or more items together and none of them is is the limit string data i would like to join then by "/". Something like this:

const stringLimit = "aa"; let arrayData =["b","c","aa","aa","d","c","aa","f"];

result:

arrayResult=["b/c","d/c","f];

I have try this, however, I think that there should be a better way

let stringItem;
let totalRouteDevice = new Array();
for (let index = 0; index < arrayData.length; index++) {
    const item = arrayData [index];
    if(item!=='aa' && item !== 'bb') {
      stringItem = stringItem!=""?`${stringItem}/${item}`:stringItem
    } else if(stringRouteItem!=="") {
      totalRoute.push(stringItem);
      stringItem ="";
    }
}

I have try this, however, I think that there should be a better way

let stringItem;
let totalRouteDevice = new Array();
for (let index = 0; index < arrayData.length; index++) {
    const item = arrayData [index];
    if(item!=='aa' && item !== 'bb') {
      stringItem = stringItem!=""?`${stringItem}/${item}`:stringItem
    } else if(stringRouteItem!=="") {
      totalRoute.push(stringItem);
      stringItem ="";
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Not saying this is better but you could group your data using reduce, splitting it by stringLimit, and then joining the groups by / as follows:

const stringLimit = 'aa'

const arrayData = ["b","c","aa","aa","d","c","aa","f"]

let arr = []

arrayData.reduce((acc, item, i) => {
  if (item !== stringLimit) {
    acc.push(item)
  } else {
    if (acc.length) {
      arr.push(acc)
    }
    acc = []
  }

  if (item !== stringLimit && i === arrayData.length - 1) {
    arr.push(acc)
  }

  return acc
}, [])

let result = arr.map((i) => i.join('/'))

console.log(result)

about 4 years ago · Juan Pablo Isaza Report
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!