Search code examples
javascriptmultidimensional-arrayarray-splice

Split 1D Binary Array into 2D Array of Consecutive Ones Only


Imagining I want to split a binary ID array arr into 2D array newArr of consecutive ones interspersed between zeros. Furthermore I want to collect the corresponding indices of the selected ones in a 2D array named Index.

arr = [1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1];

Expected results:

newArr = [[1, 1, 1] , [1, 1],[1, 1]];

Index = [[3,4,5], [7,8],[10,11]];

My attempt of this problem is attached, but is no good.

var arr = [1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1];

var newArr = [];
let i = arr.length
while(i--){
  if ((arr[i]===1) && (arr[i+1]===1)){
  	newArr.push(arr.splice(0,3));
  }
}

console.log(newArr)


Solution

  • You could reduce the array and collect the items which have a predecessor or a successor.

    const
        getConnectedParts = array => array.reduce((r, v, i, a) => {
            if (!v || !a[i - 1] && !a[i + 1]) return r;
            if (!a[i - 1]) {
                r.values.push([]);
                r.indices.push([]);
            }
            r.values[r.values.length - 1].push(v);
            r.indices[r.indices.length - 1].push(i);
            return r;
        }, { values:[], indices: [] });
    
    var array = [1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1],
        { values, indices } = getConnectedParts(array);
    
    values.map(a => console.log(...a));
    indices.map(a => console.log(...a));
    .as-console-wrapper { max-height: 100% !important; top: 0; }