[英]Sort nested object by date in javascript
如何按日期對數據進行排序並找到連續日期之間的最大值計數? 示例數據:
const data = {
'addias':{
'2022-1-10': ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
'2022-1-09': ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
'2021-12-29': ['a'],
'2021-12-28': ['y', 'u', 'v', 'd', 'f', 'f', 'g'],
'2021-1-08': ['x', 't', 's', 'd', 'e', 'f', 'g'],
},
'nike':{
'2022-1-20': ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
'2022-1-15': ['a', 'b', 'c'],
'2022-1-14': ['a', 'b'],
'2022-1-10': ['y', 'b', 'x', 'z', 'e', 'f', 'g'],
}
}
結果就像
const result = {
'addias':{
'firstDate': '2022-1-09',
'secondDate':'2022-1-10',
'total':14 ,
},
'nike':{
'firstDate': '2022-1-14',
'secondDate':'2022-1-15',
'total':5,
}
}
試圖:
Object.entries(data).forEach((item) => {
const [ brand, dates ] = item; /** {'2022-1-10': array } */
let sorted = Object.entries(dates).sort((a,b) => new Date(a[0]) - new Date(b[0]))
/** find value count for each sorted date */
/** find if the dates are consecutive */
/** build new object with result property */
})
您可以這樣做,盡管您可能想編寫自定義排序 function
const data = { 'addias':{ '2022-1-10': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], '2022-1-09': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], '2021-12-29': ['a'], '2021-12-28': ['y', 'u', 'v', 'd', 'f', 'f', 'g'], '2021-1-08': ['x', 't', 's', 'd', 'e', 'f', 'g'], }, 'nike':{ '2022-1-20': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], '2022-1-15': ['a', 'b', 'c'], '2022-1-14': ['a', 'b'], '2022-1-10': ['y', 'b', 'x', 'z', 'e', 'f', 'g'], } } const result = {}; Object.keys(data).forEach(sneaker => { const dates = Object.keys(data[sneaker]); dates.sort(); result[sneaker] = { firstDate: dates[0], secondDate: dates[1], total: dates.length }; }); console.log(result);
我認為在計數之前找出日期對會更有效,我認為這應該可以解決問題:
const data = { 'addias': { '2022-1-10': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], '2022-1-09': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], '2021-12-29': ['a'], '2021-12-28': ['y', 'u', 'v', 'd', 'f', 'f', 'g'], '2021-1-08': ['x', 't', 's', 'd', 'e', 'f', 'g'], }, 'nike': { '2022-1-20': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], '2022-1-15': ['a', 'b', 'c'], '2022-1-14': ['a', 'b'], '2022-1-10': ['y', 'b', 'x', 'z', 'e', 'f', 'g'], } }; function maxValueBetweenConsecutiveDates(input) { const result = {}; for (const brand in input) { const dates = Object.keys(input[brand]).map(e => ({ date: new Date(e), original: e })).sort((a, b) => a.date - b.date); const pairs = []; for (let i = 1; i < dates.length; i++) { if (dates[i].date - dates[i - 1].date === 86400000) { pairs.push([dates[i - 1], dates[i]]); } } const quantities = pairs.map(pair => ({ firstDate: pair[0].original, secondDate: pair[1].original, total: input[brand][pair[0].original].length + input[brand][pair[1].original].length })); const max = Math.max(...quantities.map(e => e.total)); const quantity = quantities.find(e => e.total === max); result[brand] = quantity; } return result; } console.log(maxValueBetweenConsecutiveDates(data));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.