-2

Having a an array of objects with the following structure:

[{value: "a", start: 1950, end: 1954, description: "aaa"},
{value: "b", start: 1953, end: 1956, description: "bbb"},
{value: "c", start: 1960, end: 1962, description: "ccc"}]

how can I populate the array to get the following result using javascript? I want to populate the array creating a new object per each year contained between start and end.

[{value: "a", year: 1950, start: 1950, end: 1954, description: "aaa"},
{value: "a", year: 1951, start: 1950, end: 1954, description: "aaa"},
{value: "a", year: 1952, start: 1950, end: 1954, description: "aaa"},
{value: "a", year: 1953, start: 1950, end: 1954, description: "aaa"},
{value: "a", year: 1954, start: 1950, end: 1954, description: "aaa"},
{value: "b", year: 1953 ,start: 1953, end: 1956, description: "bbb"},
{value: "b", year: 1954, start: 1953, end: 1956, description: "bbb"},
{value: "b", year: 1955, start: 1953, end: 1956, description: "bbb"},
{value: "b", year: 1956, start: 1953, end: 1956, description: "bbb"},
{value: "c", year: 1960, start: 1960, end: 1962, description: "ccc"},
{value: "c", year: 1961, start: 1960, end: 1962, description: "ccc"},
{value: "c", year: 1962, start: 1960, end: 1962, description: "ccc"}]

My understanding is that I should write a for loop to map the results but I am having trouble seeing how I can account for the start and end variables of each original value.

console.log
  • 177
  • 2
  • 16

1 Answers1

3

Using flatMap() with Array.from() should get you there.

const data = [
  {value: "a", start: 1950, end: 1954, description: "aaa"},
  {value: "b", start: 1953, end: 1956, description: "bbb"},
  {value: "c", start: 1960, end: 1962, description: "ccc"}
];

const result = data.flatMap(({value, start, end, description}) => {
  return Array.from({length: end - start + 1}, (_, i) => start + i)
              .map(year => ({value, year, start, end, description}));
});
  
console.log(result);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156