假设我有一个这样的数组:
var arr = [
{type:"orange", title:"First"},
{type:"orange", title:"Second"},
{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}
];
我想把它分成数组,这些数组的对象具有相同的类型,所以:
[{type:"orange", title:"First"},
{type:"orange", title:"Second"}]
[{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}]
但我想泛泛地这样做,这样就不会有指定橙色或香蕉的if语句。
// not like this
for (prop in arr){
if (arr[prop] === "banana"){
//add to new array
}
}
有什么想法?JQuery和下划线都是要使用的选项。
发布于 2013-02-05 06:03:10
这里假设有一个对象数组:
function groupBy(array, property) {
var hash = {};
for (var i = 0; i < array.length; i++) {
if (!hash[array[i][property]]) hash[array[i][property]] = [];
hash[array[i][property]].push(array[i]);
}
return hash;
}
groupBy(arr,'type') // Object {orange: Array[2], banana: Array[2]}
groupBy(arr,'title') // Object {First: Array[1], Second: Array[1], Third: Array[1], Fourth: Array[1]}
发布于 2013-02-05 06:04:02
只需构建一个字典,根据对象的标题保存对象。你可以这样做:
js
var arr = [
{type:"orange", title:"First"},
{type:"orange", title:"Second"},
{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}
];
var sorted = {};
for( var i = 0, max = arr.length; i < max ; i++ ){
if( sorted[arr[i].type] == undefined ){
sorted[arr[i].type] = [];
}
sorted[arr[i].type].push(arr[i]);
}
console.log(sorted["orange"]);
console.log(sorted["banana"]);
jsfiddle演示:http://jsfiddle.net/YJnM6/
发布于 2020-03-25 00:59:09
ES6解决方案:
function groupBy(arr, property) {
return arr.reduce((acc, cur) => {
acc[cur[property]] = [...acc[cur[property]] || [], cur];
return acc;
}, {});
}
或者完全ES6fy:
const groupBy = (arr, property) => {
return arr.reduce((acc, cur) => {
acc[cur[property]] = [...acc[cur[property]] || [], cur];
return acc;
}, {});
}
我希望它能有所帮助!
https://stackoverflow.com/questions/14696326
复制相似问题