Home > Blockchain >  Split array into smaller arrays separated by ''
Split array into smaller arrays separated by ''

Time:12-03

How to split an array into smaller arrays separated by ""?

I have an array which looks like this:


`[
  '1000', '2000',  '3000',
  '',     '4000',  '',
  '5000', '6000',  '',
  '7000', '8000',  '9000',
  '',     '10000'
]
`

I need arrays which would look like this:


`  ['1000', '2000',  '3000',]
  [ '4000'] 
  ['5000', '6000' ]
  ['7000', '8000',  '9000']
  [ '10000']
`

Any help is useful

CodePudding user response:

We can first find all the index for value is empty,then using Array.slice() to do it.

Below is a simple reference for you(not fully tested yet,such as multiple empty elements appear continuously)

let arr = [
  '1000', '2000',  '3000',
  '',     '4000',  '',
  '5000', '6000',  '',
  '7000', '8000',  '9000',
  '',     '10000'
]

const convertArray = data => {
  let pos = []
  data.forEach((v,i) =>{
     if(!v){
       pos.push(i)
     }
  })

  let result = []
  let prev = 0
  for(p of pos){
    result.push(data.slice(prev,p))
    prev = p   1
  }
  result.push(data.slice(prev))
  return result
}


console.log(convertArray(arr))

CodePudding user response:

this worked for me , hope this works for your too..

   const arr = [
    '1000', '2000', '3000',
    '', '4000', '',
    '5000', '6000', '',
    '7000', '8000', '9000',
    '', '10000'
]

const newArr = []
let index = 0

for (let i = 0; i < arr.length; i  ) {
    if (arr[i] == '') {
        const newArrSet = []
        for(let j = i ; j > index ; j-- ){
            console.log('revese' , arr[j] ,  i)
            newArrSet.push(arr[j])
        }
        newArr.push(newArrSet)
        index = i
    }

}
   const mappedArray = newArr.map((item)=>{
     return item.filter(item=> item !== '')
   })

   console.log(mappedArray)
  • Related