Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chunks of an Array of objects using an object property as the "delimiter"

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}]
]
like image 712
Shlomi Schwartz Avatar asked Aug 30 '16 11:08

Shlomi Schwartz


2 Answers

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);
like image 83
Ori Drori Avatar answered Sep 30 '22 06:09

Ori Drori


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; }
like image 27
Nina Scholz Avatar answered Sep 30 '22 06:09

Nina Scholz