skip to Main Content

I’m new. I have an array

[1, 0, 0, 0, 0, 2, 4, 0, 0, 0, 0, 0, 0, 0, 5, 6]

I want to get a two-dimensional array from it

[[0, 0, 0,0],
[0, 0, 0, 0, 0, 0, 0,]]

how to do this without regular expressions

I have a solution where I use regular expressions with the split method, but need a variant without regular expressions and so that you get an array of zeros, not a string of zeros

    function zeroGroups(arr){
        const allZerosGroups = arr
          .map(item => item !== 0 ? '-' : 0)
          .join('')
          .split(/[^0]/)
          .filter(item => item.length !== 0)
          
        return allZerosGroups
    }
console.log(zeroGroups([1, 0, 0, 0, 0, 2, 4, 0, 0, 0, 0, 0, 0, 0, 5, 6])) // [ '0000', '0000000' ]

2

Answers


  1. Loop through and check along the way. This is one way to do it:

    var arr =  [1, 0, 0, 0, 0, 2, 4, 0, 0, 0, 0, 0, 0, 0, 5, 6]
        var container = []
        containerCount = 0
        arrCount = 0
        var dArr = []
        arrLen = arr.length
        loop1:
        for (i = 0;i< arrLen;i++) {
            if (arr[i] == 0) {                                                              
                dArr[arrCount] = arr[i]  
                arrCount++    
                console.log(dArr)                 
            } else if (arrCount == 0) {
                continue
            } else {
                container[containerCount] = dArr                        
                arrCount = 0
                containerCount++    
                dArr = []                
            }                
        }
    
        console.log(container)
    
    Login or Signup to reply.
  2. Hope, this helps.

    let arr1 = [1, 0, 0, 0, 0, 2, 4, 0, 0, 0, 0, 0, 0, 0, 5, 6];
    
    let res = [];
    let temp = []; 
    
    arr1.map((item)=>{
      if(item === 0){temp.push(item)}
      else {
        if (temp.length!=0){
          res.push(temp); 
          temp = [];
        }
      }
     });
    
    console.log(res);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search