我有一个非常大的数组,类似于这样
var array = [
{ id: 1, category: 'Apple' },
{ id: 2, category: 'Orange' },
{ id: 3, category: 'Orange' },
{ id: 4, category: 'Grape' },
{ id: 5, category: 'Grape' },
]
我希望按元素的值将项目分开,就像这样
var newArray = [
[
{ id: 1, category: 'Apple' },
],
[
{ id: 2, category: 'Orange' },
{ id: 3, category: 'Orange' },
],
[
{ id: 4, category: 'Grape' },
{ id: 5, category: 'Grape' },
],
]
这是我目前使用的:
var array = [
{ id: 1, category: 'Apple' },
{ id: 2, category: 'Orange' },
{ id: 3, category: 'Orange' },
{ id: 4, category: 'Grape' },
{ id: 5, category: 'Grape' }
];
var categories = [];
array.forEach(function(item) {
categories.push(item.category);
});
var uniqueCategories = categories.filter(function(item, pos) {
return categories.indexOf(item) == pos;
});
var newArray = []
uniqueCategories.forEach(function(category, index) {
array.forEach(function(item) {
if (item.category === category) {
if (!newArray[index]) {
newArray[index] = [];
}
newArray[index].push(item);
}
});
});
但是在1000-10000项的大数组上运行非常缓慢。
如何以最佳性能完成它?