Reputation: 269
I have two javascript arrays of objects:
var fullDateRange=[{date:"4/1/18",value:0},{date:"4/2/18",value:0},{date:"4/3/18",value:0},{date:"4/4/18",value:0},{date:"4/5/18",value:0}]
and
var actualDateRange=[{date:"4/1/18",value:1},{date:"4/3/18",value:3},{date:"4/5/18",value:5}]
I'm trying to loop through the fullDateRange array, see if any of the actualDateRange dates exist, and increment the value. But I keep getting duplicates with this code:
function outputDeltaDates(fullDateObj, responseObj) {
var dateArr = [],
valueArr = [];
$.each(fullDateObj, function(index) {
var fullDate = this;
var counter = 0
$.each(responseObj, function(index) {
var fullResponse = this;
if (fullResponse['date'] == fullDate['date']) {
valueArr.push(fullResponse['value'])
dateArr.push(fullDate['date'])
} else {
if (!dateArr.includes(fullDate['date'])) {
valueArr.push(0)
dateArr.push(fullDate['date'])
}
}
})
})
return [valueArr, dateArr]
}
Upvotes: 0
Views: 46
Reputation: 73241
To increment the objects value property if the date exists in the other array, simply loop it once and increment value if the date is found in actualDateRange
var fullDateRange=[{date:"4/1/18",value:0},{date:"4/2/18",value:0},{date:"4/3/18",value:0},{date:"4/4/18",value:0},{date:"4/5/18",value:0}]
var actualDateRange=[{date:"4/1/18",value:1},{date:"4/3/18",value:3},{date:"4/5/18",value:5}]
fullDateRange.forEach(e => {
let act = actualDateRange.find(a => a.date === e.date);
if (act) e.value += act.value;
})
console.log(fullDateRange);
Upvotes: 1
Reputation: 10975
To achieve expected result, push incremented counter to valueArr i.e
valueArr.push(++counter)
instead of fullResponse['value'] (which will push actualDateRange value)
var fullDateRange=[{date:"4/1/18",value:0},{date:"4/2/18",value:0},{date:"4/3/18",value:0},{date:"4/4/18",value:0},{date:"4/5/18",value:0}]
var actualDateRange=[{date:"4/1/18",value:1},{date:"4/3/18",value:3},{date:"4/5/18",value:5}]
function outputDeltaDates(fullDateObj, responseObj) {
var dateArr = [],
valueArr = [];
$.each(fullDateObj, function(index) {
var fullDate = this;
var counter = 0
$.each(responseObj, function(index) {
var fullResponse = this;
if (fullResponse['date'] == fullDate['date']) {
valueArr.push(++counter)
dateArr.push(fullDate['date'])
} else {
if (!dateArr.includes(fullDate['date'])) {
valueArr.push(0)
dateArr.push(fullDate['date'])
}
}
})
})
return [valueArr, dateArr]
}
console.log(outputDeltaDates(fullDateRange, actualDateRange))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
code sample - https://codepen.io/nagasai/pen/rvVqdW?editors=1010
Upvotes: 0