javascriptarrayssortingsegment

Split an arbitrary array into segments of two kinds


Let's say I have an arbitrary integer array filled with zeros and positive numbers. Need to split these arrays into solid and dashed indexed segments following left rule.

let array1 = [0, 0, 14, 54, 23, 0, 34, 11, 12, 54];

let array2 = [14, 0, 43, 13, 0, 0, 54, 0];

enter image description here

So the considerable output for array1 have to be

let out = {solid: [[1, 2, 3, 4], [5, 6, 7, 8, 9]], dashed: [[0, 1], [4, 5]]};

and for array2

let out = {solid: [[1, 2, 3], [5, 6]], dashed: [[0, 1], [3, 4, 5], [6, 7]]}

In other words, I need a solution for going through an array and split it into segments. If the right value of i + 1 is 0, then the segment or part of the segment must be considered as dashed, if any positive integer-solid. The segments could be of any length as long as values satisfy the condition.


Solution

  • Not sure if this covers every scenario but you could try something like this using a for and a while loops and finding a occurrences where the current elements is 0 and the next element is not, and then from that point you search for zeros backwards and not zeros forwards.

    let array1 = [0, 0, 14, 54, 23, 0, 34, 11, 12, 54];
    let array2 = [14, 0, 43, 13, 0, 0, 54, 0];
    
    function parse(data) {
      const dashed = []
      const solid = []
    
      for (let i = 0; i < data.length; i++) {
        const current = data[i],
          next = data[i + 1]
    
        if (current === 0 && next !== 0) {
          let ineg = i,
            ipos = i,
            arrneg = [i],
            arrpos = [i]
    
          while (data[ineg--] === 0 && ineg > -1) {
            arrneg.unshift(ineg)
          }
    
          while (data[++ipos] !== 0 && ipos < data.length) {
            arrpos.push(ipos)
          }
    
          if (arrneg.length > 1) dashed.push(arrneg)
          if (arrpos.length > 1) solid.push(arrpos)
        }
      }
    
      return {
        solid,
        dashed
      }
    }
    
    console.log(JSON.stringify(parse(array1)))
    console.log(JSON.stringify(parse(array2)))