Reputation: 446
I have a list of items I need to loop thru. I need to search if an array of items contains an array of items. This is the array, first value is timestamp, second is a count:
const i = [
[1614719782079, 1],
[1614719782085, 1],
[1614719782091, 2],
[1614719782096, 2],
]
And I have a forEach loop that goes thru all this data from my backend and I need to check if the timestamp exists in the array(the first value) and if it does, add to the second value of the array(count). This is an example data from backend:
const mockData = [
{
...someData,
details: {
eventTimestamp: 1614719782079,
equipmentId: 5,
otherUselessData...
}
},
{
...someData,
details: {
eventTimestamp: 1614719782079,
equipmentId: 5,
otherUselessData...
}
}
]
Basically if eventTimestamp
in the mockData exists in the i
, then increment the second value in that array. PS dont ask about the horrible structure of the this data lol. This is all I have to work with
Upvotes: 2
Views: 182
Reputation: 393
here is my edited solution, sorry , didnt understand it in first time
const i = [
[1614719782079, 1],
[1614719782085, 1],
[1614719782091, 2],
[1614719782096, 2],
]
const mockData = [
{
details: {
eventTimestamp: 1614719782079,
equipmentId: 5,
}
},
{
details: {
eventTimestamp: 1614719782079,
equipmentId: 5,
count: 1,
}
}
]
mockData.forEach(mock => {
const el = i.find(e => e[0] === mock.details.eventTimestamp);
if(el) {
el[1]++
}
})
console.log(i)
Upvotes: 1
Reputation: 28414
Here is a possible solution:
Map
of the elements of i
where the first item is the key
and the second is the value
mockData
, and in each iteration, if the eventTimestamp
is in this map, increment its value
i
to the entries
of this maplet i = [
[1614719782079, 1],
[1614719782085, 1],
[1614719782091, 2],
[1614719782096, 2],
];
const mockData = [
{ details: { eventTimestamp: 1614719782079, equipmentId: 5 } },
{ details: { eventTimestamp: 1614719782079, equipmentId: 5 } }
];
const updateTimestampCounts = (arr=[]) => {
const map = new Map();
i.forEach(([ timestamp, count ]) => map.set(timestamp, count));
arr.forEach(({ details={} }) => {
const { eventTimestamp } = details;
const count = map.get(eventTimestamp);
if(count) map.set(eventTimestamp, count+1);
});
i = [...map.entries()];
}
updateTimestampCounts(mockData)
console.log(i);
Upvotes: 2
Reputation: 593
Following code should do the trick:
mockData.forEach(mock => {
const el = i.find(e => e[0] === mock.details.eventTimestamp);
if(el) {
el[1]++
}
})
Upvotes: 2