array group by key javascript
array group by key javascript
calendar
Array.reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
result = array.reduce((h, obj) => Object.assign(h, { [obj.key]:( h[obj.key] || [] ).concat(obj) }), {})
var cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }],
result = cars.reduce(function (r, a) {
r[a.make] = r[a.make] || [];
r[a.make].push(a);
return r;
}, Object.create(null));
console.log(result);
groupBy
https://learnwithparam.com/blog/how-to-group-by-array-of-objects-using-a-key/
const groupBy = (array, key) => {
return array.reduce((result, currentValue) => {
(result[currentValue.color] = result[currentValue.color] || []).push(
currentValue
);
console.log(result);
return result;
}, {});
};
// this step of code can be restructured to multiple lines, see below for the multi line code
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
);
// This is how the above code in multiple line
if (!result[currentValue[key]]) {
result[currentValue[key]] = [];
}
result[currentValue[key]].push(currentValue);
_.groupBy
https://lodash.com/docs/4.17.2#groupBy
OK
const log = console.log;
const events = [
{
"id": 210404,
"productId": 13602,
"activityEventId": 8623896,
"ticketCategoryId": 5246754,
"ticketGroupId": 81798755,
"start": 1617532218562,
"end": 1617532218562,
"ticketsNumber": 100,
"lowPrice": 127.00,
"status": 0,
"priceLowest": false,
"hasTicket": true,
"availableNumbers": [
1,
2,
3,
4,
5,
6
]
},
{
"id": 210403,
"productId": 13602,
"activityEventId": 7623896,
"ticketCategoryId": 5246754,
"ticketGroupId": 71798755,
"start": 1617432218562,
"end": 1617432218562,
"ticketsNumber": 100,
"lowPrice": 127.00,
"status": 0,
"priceLowest": false,
"hasTicket": true,
"availableNumbers": [
1,
2,
3,
4,
5,
6
]
},
{
"id": 191837,
"productId": 13602,
"activityEventId": 1623896,
"ticketCategoryId": 5246754,
"ticketGroupId": 61798755,
"start": 1585497600000,
"end": 1585497600000,
"ticketsNumber": 100,
"lowPrice": 127.00,
"status": 0,
"priceLowest": false,
"hasTicket": true,
"availableNumbers": [
1,
2,
3,
4,
5,
6
]
},
{
"id": 191812,
"productId": 13602,
"activityEventId": 1623891,
"ticketCategoryId": 5246729,
"ticketGroupId": 61798730,
"start": 1585584000000,
"end": 1585584000000,
"ticketsNumber": 100,
"lowPrice": 127.00,
"status": 0,
"priceLowest": false,
"hasTicket": true,
"availableNumbers": [
1,
2,
3,
4,
5,
6
]
},
{
"id": 191701,
"productId": 13602,
"activityEventId": 5623852,
"ticketCategoryId": 5246618,
"ticketGroupId": 51798619,
"start": 1585670400000,
"end": 1585670400000,
"ticketsNumber": 100,
"lowPrice": 127.00,
"status": 0,
"priceLowest": false,
"hasTicket": true,
"availableNumbers": [
1,
2,
3,
4,
5,
6
]
},
{
"id": 191749,
"productId": 13602,
"activityEventId": 4623876,
"ticketCategoryId": 5246666,
"ticketGroupId": 41798667,
"start": 1585756800000,
"end": 1585756800000,
"ticketsNumber": 100,
"lowPrice": 127.00,
"status": 0,
"priceLowest": false,
"hasTicket": true,
"availableNumbers": [
1,
2,
3,
4,
5,
6
]
},
{
"id": 191737,
"productId": 13602,
"activityEventId": 3623870,
"ticketCategoryId": 5246654,
"ticketGroupId": 31798655,
"start": 1585843200000,
"end": 1585843200000,
"ticketsNumber": 100,
"lowPrice": 127.00,
"status": 0,
"priceLowest": false,
"hasTicket": true,
"availableNumbers": [
1,
2,
3,
4,
5,
6
]
},
{
"id": 262539,
"productId": 13602,
"activityEventId": 1651249,
"ticketCategoryId": 5319475,
"ticketGroupId": 11872015,
"start": 1588089600000,
"end": 1588089600000,
"ticketsNumber": 100,
"lowPrice": 127.00,
"status": 0,
"priceLowest": false,
"hasTicket": true,
"availableNumbers": [
1,
2,
3,
4,
5,
6
]
}
];
// log(`events`, events)
const dateShaper = (timestamp = ``) => {
const date = new Date(timestamp)
const dateString = date.toLocaleDateString();
const timeString = date.toLocaleTimeString();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const weekDays = ["日", "一", "二", "三", "四", "五", "六"];
const weekDay = weekDays[date.getDay()];
return {
dateString,
timeString,
year,
month,
day,
weekDay,
};
}
const thisYear = new Date().getFullYear();
const tabs = events.map((obj, i) => {
const {
start,
} = obj;
const date = new Date(start);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const tabName = thisYear === year ? `${month}月` : `${year}年${month}月`;
// const tabGroupKey = thisYear !== year ? `${year}_` + `${month}`.padStart(2, `0`) : `${month}`.padStart(2, `0`);
const tabGroupKey = `${year}_` + `${month}_`.padStart(3, `0`) + `${day}`.padStart(2, `0`);
// const tabGroupKey = `${year}_${month}_${day}`;
return {
...obj,
tabName,
tabGroupKey,
};
});
// log(`tabs`, tabs)
const sortedArray = tabs.sort((a, b) => a.start > b.start ? 1 : -1);
// log(`sortedArray`, sortedArray)
// const groupBy = (array, key) => {
// return array.reduce((result, currentValue) => {
// result[currentValue.key] = result[currentValue.key] || [];
// result[currentValue.key].push(
// currentValue,
// );
// // console.log(result);
// return result;
// }, {});
// };
// const groupBy = (array, key) => {
// return array.reduce((result, currentValue) => {
// result[currentValue.key] = result[currentValue.key] || [];
// result[currentValue.key].push(
// currentValue,
// );
// // console.log(result);
// return result;
// }, []);// array
// };
const groupBy = (array, key) => array.reduce((h, obj) => Object.assign(h, { [obj[key]]:( h[obj[key]] || [] ).concat(obj) }), []);
// const groupBy = (array, key) => array.reduce((h, obj) => Object.assign(h, { [obj[key]]:( h[obj[key]] || [] ).concat(obj) }), {});
// const groupBy = (array, key) => array.reduce((h, obj) => Object.assign(h, { [obj.key]:( h[obj.key] || [] ).concat(obj) }), {});
//
const groupedArray = groupBy(sortedArray, `tabName`);
// const groupedArray = groupBy(sortedArray, `tabGroupKey`);
log(`groupedArray`, groupedArray)
// log(`groupedArray[0]`, groupedArray[0])
Object.keys(groupedArray).map((month, i) => {
log(`tab month`, month, i)
})
Object.values(groupedArray).map((month, i) => {
log(`tab month`, month, i)
})
Object.entries(groupedArray).map((month, i) => {
const {
// key,
// value,
} = month;
log(`tab month key`, month[0], i)
log(`tab month value`, month[1], i)
})

array group by key javascript的更多相关文章
- how to group date array by month in javascript
how to group date array by month in javascript https://stackoverflow.com/questions/14446511/most-eff ...
- 谷歌IAP:skusBundle array associated with key ITEM_ID_LIST cannot contain more than 20 items.
这几天在接谷歌的支付,在拉谷歌商品列表的时候转菊花,长时间不返回(querySkuDetails),一开始以为因为IAP有key不对导致的,查了下发现没有问题. 再看logcat,发现了这行: Inp ...
- [JavaScript] Array.prototype.reduce in JavaScript by example
Let's take a closer look at using Javascript's built in Array reduce function. Reduce is deceptively ...
- ExtJS学习-----------Ext.Array,ExtJS对javascript中的Array的扩展
关于ExtJS对javascript中的Array的扩展.能够參考其帮助文档,文档下载地址:http://download.csdn.net/detail/z1137730824/7748893 因为 ...
- 复习 Array,重学 JavaScript
1 数组与对象 在 JavaScript 中,一个对象的键只能有两种类型:string 和 symbol.下文只考虑键为字符串的情况. 1.1 创建对象 在创建对象时,若对象的键为数字,或者由 字母+ ...
- ExtJS学习-----------Ext.Array,ExtJS对javascript中的Array的扩展(实例)
(1)clean var arr = [1,2,null,3,'']; alert(Ext.Array.clean(arr)); //clean的对象:(value === null) || (val ...
- javascript数组去重 String字符串去掉两端空格 javascript Array二分法排序 比较 javascript 求和
通过原形添加方法: ==================数组去重(对象去重法)======================= Array.prototype.unique=function(){ va ...
- JavaScript求数组Array的并集(javascript面试常见题目)
var Utils = { joinArray:function(source,target){ for(var i = 0;i<source.length;i++){ var oa = sou ...
- Azure DevOps的variable group实现array和hashtable参数的传递
Azure Devops中的variable group建议或者只能(?)添加string类型的value.基于此我们想在variable group实现array或者hashtable的传递的核心思 ...
随机推荐
- Flutter GetX使用---简洁的魅力!
前言 使用Bloc的时候,有一个让我至今为止十分在意的问题,无法真正的跨页面交互!在反复的查阅官方文档后,使用一个全局Bloc的方式,实现了"伪"跨页面交互,详细可查看:flutt ...
- Java AQS的原理
首先可以看: http://ifeve.com/java-special-troops-aqs/ 再看 <Java并发编程的艺术>第5章 核心:同步器的acquire方法: 首先调用自 ...
- yum安装docker-ce-18.03.0
yum install -y yum-utils device-mapper-persistent-data lvm2 yum-config-manager --add-repo http://mir ...
- 分布式缓存 — redis
redis是一种支持Key-Value等多种数据结构的存储系统.可用于缓存,事件发布或订阅,高速队列等场景.该数据库使用ANSI C语言编写,支持网络,提供字符串,哈希,列表,队列,集合结构直接存取, ...
- nohup和&后台运行,进程查看及终止
文章目录 一.nohup 1.1用途:不挂断地运行命令. 1.2语法:nohup Command [ Arg - ] [ & ] 1.3退出状态:该命令返回下列出口值: 二.& 2.1 ...
- Spring Boot 之遇见JSON
MVC框架中,Spring Boot内置了jackson来完成JSON的序列化和反序列化操作,并且,在与其他技术集成的时候,如Redis.MongoDB.Elasticsearch等对象序列化,都可使 ...
- css按钮样式
style='height:22px;padding:1 17px;font-size: 8px;font-weight: 100;line-height: 25px;'http://www.boot ...
- (6)dd命令安装Linux
1.面对大批量服务器的安装,人们往往热衷于选择"无人值守安装"的方式,而此方式需要对服务器进行过多的配置,并不适合初学者. 无人值守安装(Kickstart),又称全自动安装,其工 ...
- thymeleaf第一篇:什么是-->为什么要使用-->有啥好处这玩意
Thymeleaf3.0版本官方地址 1 Introducing Thymeleaf Thymeleaf 是一个跟 Velocity.FreeMarker 类似的模板引擎,它可以完全替代 JSP . ...
- cassandra权威指南读书笔记--cassandra查询语言
cassandra使用一个特殊主键(复合键)表示宽行,宽行也叫分区.复合键由一个分区键和一组可选的集群列组成.分区键用于确定存储行的节点,分区键也可以包含多个列.集群键用于控制数据如何排序以及在分区中 ...