说我有这样的数组:
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和Underscore都是可以使用的选项。
答案 0 :(得分:35)
答案 1 :(得分:32)
对于Array.reduce(...)
来说,这是一项轻松的工作:
function groupBy(arr, property) {
return arr.reduce(function(memo, x) {
if (!memo[x[property]]) { memo[x[property]] = []; }
memo[x[property]].push(x);
return memo;
}, {});
}
var o = groupBy(arr, 'type'); // => {orange:[...], banana:[...]}
o.orange; // => [{"type":"orange","title":"First"},{"type":"orange","title":"Second"}]
o.banana; // => [{"type":"banana","title":"Third"},{"type":"banana","title":"Fourth"}]
当然,如果您的目标浏览器不支持ECMAScript 262第5版,那么您必须自己实施“减少”,或使用polyfill库,或选择其他答案。
[更新] 以下是适用于任何版本JavaScript的解决方案:
function groupBy2(xs, prop) {
var grouped = {};
for (var i=0; i<xs.length; i++) {
var p = xs[i][prop];
if (!grouped[p]) { grouped[p] = []; }
grouped[p].push(xs[i]);
}
return grouped;
}
答案 2 :(得分:9)
这假设一个对象数组:
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]}
答案 3 :(得分:9)
只需构建一个字典,根据标题保存对象。你可以这样做:
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 demo:http://jsfiddle.net/YJnM6/
答案 4 :(得分:4)
ES6解决方案:
Option Explicit
Sub exportSheets()
Dim ws As Worksheet
Dim filePath As String
'get filepath from user input
filePath = Range("E6").Value
Dim answer As Variant
'ask if the user is sure about exporting
answer = MsgBox("Export all Worksheets to text files?", vbYesNo, "Run Macro")
If answer = vbYes Then
' Turn off alerts. Be aware that will overwrite existing file without warning
Application.DisplayAlerts = False
'loop through every sheet in the work book
For Each ws In ThisWorkbook.Worksheets
With ws
'skip the first page in the excel workbook
If .Index > 1 Then
.SaveAs Filename:=filePath & "\" & .Name & ".txt", FileFormat:=xlTextMSDOS, CreateBackup:=False
End If
End With
Next
Application.DisplayAlerts = True
End If
End Sub
或完全是ES6fy:
function groupBy(arr, property) {
return arr.reduce((acc, cur) => {
acc[cur[property]] = [...acc[cur[property]] || [], cur];
return acc;
}, {});
}
希望对您有帮助!
答案 5 :(得分:2)
打字稿版本。
/**
* Group object array by property
* Example, groupBy(array, ( x: Props ) => x.id );
* @param array
* @param property
*/
export const groupBy = <T>(array: Array<T>, property: (x: T) => string): { [key: string]: Array<T> } =>
array.reduce((memo: { [key: string]: Array<T> }, x: T) => {
if (!memo[property(x)]) {
memo[property(x)] = [];
}
memo[property(x)].push(x);
return memo;
}, {});
export default groupBy;
答案 6 :(得分:0)
您也可以使用 https://lodash.com/docs/4.17.15#groupBy
它将为您服务