[英]How to split an array into arrays by an objects property using javascript?
I currently have an array that resembles the array below: 我目前有一个类似于下面数组的数组:
[
{id:1,color:'red'},
{id:2,color:'blue'},
{id:3,color:'red'},
{id:4,color:'green'},
{id:5,color:'blue'},
]
I am looking for the fastest way to get something like below where I could split/sort the array by a property in the object, in this example it would be 'color' : 我正在寻找最快的方法来获得类似下面的东西,我可以通过对象中的属性对数组进行拆分/排序,在这个例子中它将是'color':
[
[
{id:1,color:'red'},
{id:3,color:'red'},
],[
{id:2,color:'blue'},
{id:5,color:'blue'},
],[
{id:4,color:'green'},
]
]
I could write a function for this but I was thinking there may be something to do this already in underscore.js, but had no luck finding it. 我可以为此编写一个函数,但我认为在underscore.js中可能有一些事情要做,但没有找到它的运气。
You need to use the groupBy
function of underscore you can find it in the docs right here . 您需要使用下划线的
groupBy
函数,您可以在此处的文档中找到它。
groupBy_.groupBy(list, iterator, [context])
groupBy_.groupBy(list,iterator,[context])
Splits a collection into sets, grouped by the result of running each value through iterator.将集合拆分为集合,按照通过迭代器运行每个值的结果进行分组。 If iterator is a string instead of a function, groups by the property named by iterator on each of the values.
如果迭代器是字符串而不是函数,则按每个值上的迭代器命名的属性进行分组。
[
{id:1,color:'red'},
{id:2,color:'blue'},
{id:3,color:'red'},
{id:4,color:'green'},
{id:5,color:'blue'},
]
_.groupBy(a, function(x){ return x.color; });
You can combine the _.groupBy
with the _.toArray
function: 您可以将
_.groupBy
与_.toArray
函数结合使用:
var dict = [
{id:1,color:'red'},
{id:2,color:'blue'},
{id:3,color:'red'},
{id:4,color:'green'},
{id:5,color:'blue'},
];
var grouped = _.groupBy(dict, function(x){ return x.color; });
var result = _.toArray(grouped);
You can get the required results using ES5 features without need of third party libraries: 您可以使用ES5功能获得所需的结果,而无需第三方库:
var data = [
{id:1,color:'red'},
{id:2,color:'blue'},
{id:3,color:'red'},
{id:4,color:'green'},
{id:5,color:'blue'},
];
var temp = {};
data.forEach(function(item){
if (temp[item.color]) {
temp[item.color].push(item);
} else {
temp[item.color] = [ item ]; }
});
var result = Object.keys(temp).map(function(key){ return temp[key]; });
In order to support older browsers use ES5 shims 为了支持旧浏览器,请使用ES5填充程序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.