使用对象属性作为“分隔符”的对象数组的块

时间:2016-08-30 11:32:58

标签: javascript arrays web lodash chunks

给出以下数组:

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

如何使用lodash,每次代码不等于0时拆分数组并得到以下结果?

[
 [{id:1 , code:0},{id:1 , code:12}],
 [{id:1 , code:0},{id:1 , code:0},{id:1 , code:5}]
]

4 个答案:

答案 0 :(得分:2)

您可以使用Array.prototype.reduce(或lodash' s _.reduce()):



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);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用单个循环的普通Javascript解决方案,而不会改变原始数组。

&#13;
&#13;
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)
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用Array.splice函数的替代“原生”JS解决方案:

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));

答案 3 :(得分:0)

如果您希望减少数字元素,那么结果很好,我想你只需要减少。

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);