5

Given the following array:

var arr = [{id:1 , code:0},
           {id:1 , code:12},
           {id:1 , code:0},
           {id:1 , code:0},
           {id:1 , code:5}];

How can I use lodash, to split the array each time code is not equal to 0 and get the following results?

[
 [{id:1 , code:0},{id:1 , code:12}],
 [{id:1 , code:0},{id:1 , code:0},{id:1 , code:5}]
]
Rob
  • 14,746
  • 28
  • 47
  • 65
Shlomi Schwartz
  • 8,693
  • 29
  • 109
  • 186

4 Answers4

4

You can use Array.prototype.reduce (or lodash's _.reduce()) for this:

var arr = [{id:1 , code:0},
           {id:1 , code:12},
           {id:1 , code:0},
           {id:1 , code:0},
           {id:1 , code:5}];

var result = arr.reduce(function(result, item, index, arr) {
  index || result.push([]); // if 1st item add sub array
  
  result[result.length - 1].push(item); // add current item to last sub array
  
  item.code !== 0 && index < arr.length - 1 && result.push([]); // if the current item code is not 0, and it's not the last item in the original array, add another sub array
  
  return result;
}, []);

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
3

A solution in plain Javascript with a single loop without mutating the original array.

var arr = [{ id: 1, code: 0 }, { id: 1, code: 12 }, { id: 1, code: 0 }, { id: 1, code: 0 }, { id: 1, code: 5 }],
    grouped = arr.reduce(function (r, a, i) {
        var l = r[r.length - 1];
        if (!i || l[l.length - 1].code) {
            r.push([a]);
        } else {
            l.push(a);
        }
        return r;
    }, []);

console.log(grouped)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

An alternative "native" JS solution using Array.splice function:

var arr = [{id:1 , code:0},{id:1 , code:12}, {id:1 , code:0},{id:1 , code:0}, {id:1 , code:5}],
    chunks = [];

for (var i = 0; i < arr.length; i++) {
    arr[i].code !== 0 && chunks.push(arr.splice(0, i + 1));
}

console.log(JSON.stringify(chunks, 0, 4));
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

Well in the result if you expect reduced number elements then i guess you just have to reduce.

var arr = [{id:1 , code:0},
           {id:1 , code:12},
           {id:1 , code:0},
           {id:1 , code:0},
           {id:1 , code:5}],
reduced = arr.reduce((red,obj) => !obj.code ? red[red.length-1].length === 1 ||
                                              red[red.length-1].length === 0 ? (red[red.length-1].push(obj),red)
                                                                             : red.concat([[obj]])
                                            : (red[red.length-1].push(obj),red),[[]]);
console.log(reduced);
Redu
  • 25,060
  • 6
  • 56
  • 76