How can I convert an array of objects into an array of arrays of objects? The goal is to group the objects in the original array based on specific criteria. Objects that are similar according to these criteria will be placed inside a subarray, which becomes an element of the new array.
I am struggling with inserting an initial empty array, which should not be included, and managing temporary states of subarrays along with temporary variables used as criteria.
What am I overlooking here? Is there a more concise, perhaps less procedural, and more functional approach to accomplishing this?
const transformArray = function (array) {
let rows = [];
let parts = [];
let lastDay = null;
let i = 0;
array.forEach(function(item) {
let currentDay = new Date(item.dt_text).getDay();
if (currentDay !== lastDay) {
// Not in the same day row
rows.push(parts);
parts = [];
parts.push(item);
lastDay = currentDay;
i = rows.indexOf(parts);
return;
} else if (currentDay === lastDay){
parts.push(item);
return;
}
});
return rows;
},
The sample data that this function handles is structured like this:
[
{
"dt":1442275200,
"main":{"temp":285.66,"temp_min":282.93,"temp_max":285.66,"pressure":899.08,"sea_level":1029.64,"grnd_level":899.08,"humidity":84,"temp_kf":2.73},
"weather":[{"id":800,"main":"Clear","description":"sky is clear","icon":"01n"}],
"clouds":{"all":0},
"wind":{"speed":1.18,"deg":34.0052},
"rain":{},
"sys":{"pod":"n"},
"dt_text":"2015-09-15 00:00:00"
},
{
"dt":1442275200,
"main":{"temp":285.66,"temp_min":282.93,"temp_max":285.66,"pressure":899.08,"sea_level":1029.64,"grnd_level":899.08,"humidity":84,"temp_kf":2.73},
"weather":[{"id":800,"main":"Clear","description":"sky is clear","icon":"01n"}],
"clouds":{"all":0},
"wind":{"speed":1.18,"deg":34.0052},
"rain":{},
"sys":{"pod":"n"},
"dt_text":"2015-09-15 00:00:00"
},
{
"dt":1442228400,
"main":{"temp":285.66,"temp_min":282.93,"temp_max":285.66,"pressure":899.08,"sea_level":1029.64,"grnd_level":899.08,"humidity":84,"temp_kf":2.73},
"weather":[{"id":800,"main":"Clear","description":"sky is clear","icon":"01n"}],
"clouds":{"all":0},
"wind":{"speed":1.18,"deg":34.0052},
"rain":{},
"sys":{"pod":"n"},
"dt_text":"2015-09-14 00:00:00"
}
]