-1

Let's say we have this:

const currentYear = 2026

and we want to create an array back to 2022 like: [2026, 2025, 2024, 2023, 2022]

I have this code right now but it doesn't work as expected:

const currentYear = 2026


const newArray = [currentYear].map(i => {
  const year = i - 1;
  if(year >= 2022) return year
});

console.log([currentYear, ...newArray])
SOmeon
  • 13
  • 3

1 Answers1

0

The map function takes a callback function and applies that function to each element in the array. It then returns a new array containing the result for each element.

For example, if you wanted to increase every value in an array by 1 you could do this:

const numbers = [1, 2, 3];

const increasedNumbers = numbers.map(number => number + 1);
//increasedNumbers would hold [2,3,4]

It seems you want to make an array of numbers that start at 1 number and count backward to finish on another number. You can achieve that with a for loop like this:

const startYear = 2026;
const finishYear = 2022;
const years = [];

for (let i = startYear; i >= finishYear; i--) {
  years.push(i);
}

//years will hold [2026, 2025, 2024, 2023, 2022]
Hayden
  • 1