Вы можете использовать Array.reduce
. Вы также можете сделать эту функцию довольно универсальной, сократив ее до массива и (необязательно) деструктурируя , чтобы извлечь каждый вложенный массив в виде отдельной переменной. Таким образом, вам не нужно определять каждое имя ключа внутри функции. Однако результат может или не может считаться «чище», в зависимости от ваших целей. Например, см. Функцию getReviewsSince()
во фрагменте ниже:
// Don't mind these functions, they're just for the sake of a working example snippet
const writeLine = (() => {
const preEl = document.querySelector('.js-pre')
return (s = '') => preEl.textContent += `${s}\n`
})()
const writeArr = (name, arr) => {
writeLine(name)
arr.forEach(r => writeLine(JSON.stringify(r)))
writeLine()
}
const getExampleReviews = () => {
let i = 0
return [
{ id: i++, timestamp: 1562166556565 },
{ id: i++, timestamp: 1514985756565 },
{ id: i++, timestamp: 1514995756565 },
{ id: i++, timestamp: 1562165556565 },
{ id: i++, timestamp: 1451837356565 },
{ id: i++, timestamp: 1451837356565 },
]
}
// ---
// Get an array - each element is a nested array for the matching timestamp
const getReviewsSince = (reviews, timestamps) =>
reviews.reduce((arr, review) => {
timestamps.forEach((ts, idx) => {
if (review.timestamp >= ts) {
arr[idx].push(review)
}
})
return arr
}, timestamps.map(() => []))
// Example usage of getReviewsSince() w/ destructuring
const reviews = getExampleReviews()
const [
lastThreeMonths,
lastSixMonths,
lastYear,
lastTwoYears,
] = getReviewsSince(reviews, [
1562166556565,
1546531756565,
1514995756565,
1451837356565,
])
// Output the results for us to see
writeArr('lastThreeMonths', lastThreeMonths)
writeArr('lastSixMonths', lastSixMonths)
writeArr('lastYear', lastYear)
writeArr('lastTwoYears', lastTwoYears)