Home > Net >  Divide an array into subarray depending on string and join its items. Javascript
Divide an array into subarray depending on string and join its items. Javascript

Time:03-23

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];

CodePudding user response:

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 ="";
            }

          }

CodePudding user response:

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)

  • Related