Open1
JavaScriptでSetオブジェクトをforEachで回すときに前後の値も欲しい
Gatsbyで年月別アーカイブを作る際に前後のアーカイブページのpageContextを渡したいが、Setは順序を持たないのでやっぱり配列に変換するのが早そう
// SetをforEachで回すときに前後の値も欲しい
const years = new Set([2014, 2015, 2016, 2017, 2018, 2019, 2020]);
const yearList = Array.from(years);
let previousYear;
yearList.forEach((year, index) => {
const nextYear = yearList[index + 1];
console.log(`------${year}------`);
if (previousYear) console.log(`previous year is ${previousYear}`);
console.log(`this year is ${year}`);
if (nextYear) console.log(`next year is ${nextYear}`);
previousYear = year;
})
------2014------
this year is 2014
next year is 2015
------2015------
previous year is 2014
this year is 2015
next year is 2016
------2016------
previous year is 2015
this year is 2016
next year is 2017
------2017------
previous year is 2016
this year is 2017
next year is 2018
------2018------
previous year is 2017
this year is 2018
next year is 2019
------2019------
previous year is 2018
this year is 2019
next year is 2020
------2020------
previous year is 2019
this year is 2020