JS将数组对象时间相同的分组显示

一、需求

将时间相同的文章分组显示,即同一天的时间,只显示第一个时间。
在这里插入图片描述

二、代码

样式:

<view class="message-box" v-for="(item,index) in messageList" :key="item.id">
			<view class="label" v-if="item.isTrue">
				<!-- 需判断是否有同一天,若有,则只显示一次 -->
				{{item.releaseTime}}
			</view>
			<view class="message-body">
				<view class="message-tab">
					<view class="message-tab_title">
						<image src="../../../static/image/organization/notice/icon_gongg.png" mode=""></image>
						<view>title</view>
					</view>
					<view class="message-tab_title_left">
						time
					</view>
				</view>
				<view class="message-content">
					easyIntroduce
				</view>
				<view class="line"></view>
				<view class="message-footer">
					<view>
						查看详情
					</view>
					<image src="../../../static/image/mine/icon_12px_left_jintou.png" mode=""></image>
				</view>
			</view>
		</view>

初始数据如下:

		messageList: [{
						id: 1,
						releaseTime: "2022-01-25 11:47:39",
					},
					{
						id: 2,
						releaseTime: "2022-01-24 11:40:39",
					},
					{
						id: 3,
						releaseTime: "2022-01-24 11:41:39",
					},
					{
						id: 4,
						releaseTime: "2022-01-24 11:42:39",
					},
				],

方法:

				    // 获取年月日-时间数组(这里就截取粗暴处理了)
					const newArr = this.messageList.map(item => item.releaseTime.substr(0, 10))
					// 对时间进行去重
					const arrSet = new Set(newArr)
					// 存放首次出现时间的下标数组
					let idList = []
					// 根据首次出现时间,将下标进行存储
					arrSet.forEach(val => {
						if (newArr.indexOf(val) != -1) {
							idList.push(newArr.indexOf(val))
						}
					})
					// 与原数组比较,若下标相同,则归为一组
					this.messageList.forEach((val, idx) => {
						idList.forEach(val2 => {
							if (idx == val2) {
								//isTrue为分组标志,列表根据isTrue进行分组即可
								val.isTrue = true
							}
						})
					})
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值