I have two separate arrays: one containing values by year and order ID, and the other with different data. My goal is to combine them into a single array based on the year.
let array1 = [{orderId: 1, year: 2020, value: 15},
{orderId: 1, year: 2021, value: 20},
{orderId: 1, year: 2022, value: 25},
{orderId: 2, year: 2020, value: 30},
{orderId: 2, year: 2021, value: 35},
{orderId: 2, year: 2022, value: 40}]
let array2 = [{id: 1, year: 2020, value: 10},
{id: 2, year: 2020, value: 20},
{id: 3, year: 2020, value: 30},
{id: 1, year: 2021, value: 10},
{id: 2, year: 2021, value: 20},
{id: 3, year: 2021, value: 30},
{id: 1, year: 2022, value: 10},
{id: 2, year: 2022, value: 20},
{id: 3, year: 2022, value: 30}]
The desired end result would be:
finalArray = [{year: 2020, array1Values: [15, 30], array2Values: [10, 20, 30]},
{year: 2021, array1Values: [20, 35], array2Values: [10, 20, 30]},
{year: 2022, array1Values: [25, 40], array2Values: [10, 20, 30}]]
This involves iterating through the years, extracting the corresponding values from array1 (2 values for each orderId), and then array2 (3 values for each Id).
I am uncertain where to begin with this. At the moment, my plan is to create an object like this:
let myObject = {
year: 0,
array1Values = [],
array2Values = []
}
My approach would then be to loop through array1, instantiate myObject, and set the year. I can check if the next element in array1 exists and whether the year is greater than the current element's year before setting it.
Within that loop, I would filter array1 based on the year, push those values into array1Values, sort array2 by id, filter it based on year, and push those values into array2Values. Once completed, I can push myObject into finalArray. Is there a more efficient way to achieve this?