Reputation: 3357
Given I have two arrays of objects which have the following structure:
{
avg: 195.6
max: 195.6
min: 195.6
time: 1552448311000
}
Now for an example: The first array has data for a temperature sensor, and the second array has data for a specific engine load. To plot this data, I need the data to be basically in the following format for each point I draw: [load, temperature], so it's a temperature vs load chart.
How can I join these two arrays so that only the points where there is a matching timestamp (a pair) are taken into consideration? The idea is that I could do something like this in the end with one combined array:
mergedArray.map(x => [x.load, x.avg])
The data can have differences in the amount of data, e.g there can be a lot more temperature points than load points, so I would need to filter the temperature data first to only include the points where there is a matching timestamp point in the load series.
Example of data:
const temperatureData = [
{
avg: 195.6,
max: 195.6,
min: 195.6,
time: '1.1.2019'
},
{
avg: 300,
max: 300,
min: 300,
time: '1.2.2019'
}
]
const loadData = [
{
avg: 195.6,
max: 195.6,
min: 195.6,
time: '1.1.2019'
}
]
const expected = [{
avg: 195.6,
max: 195.6,
min: 195.6,
time: '1.1.2019',
load: 195.6
}]
so only the first temperature data was taken because it has a matching timestamp in the load data.
One pretty bay (?) way to do this would be below, any feedback?
// First filter the load by set load filter
const filteredLoad = load.filter(x => x.avg >= this.props.filter);
// Collect the timestamps of the filtered load
const loadTimeStamps = filteredLoad.map(x => x.time);
const filteredTemperatures = temperaturData.filter(x => loadTimeStamps.includes(x.time))
.map ((c, i) => {
if (!filteredLoad[i]) return null;
return {
...c,
load: filteredLoad[i].avg
}
})
Upvotes: 2
Views: 605
Reputation: 39139
You can use loops to filter and merge the data:
var newData = [];
for (var i = 0; i < temperatureData.length; i++) {
for (var j = 0; j < loadData.length; j++) {
if (temperatureData[i].time === loadData[j].time) {
newData.push(temperatureData[i]);
newData[newData.length - 1].load = loadData[j].avg
j = loadData.length;
}
}
}
Live demo: http://jsfiddle.net/BlackLabel/9xsdqwct/
Upvotes: 1