How to change value of element in array in for loop - javascript

I have the following array :
for (let i of lastBal) {
var amtToDetect = received_amt;
console.log('amt to detect', amtToDetect);
var lpcForLoop = i.lpc;
var lic_fee_for_loop = i.lic_fee;
var daysDifference_for_loop = i.lpdays;
var onlineLPC_for_loop = i.onlinelpc;
var total_amt_for_loop = i.total_amt;
console.log('lic fee for loop', i.lic_fee);
if (amtToDetect >= lic_fee_for_loop) {
var remainAmtAfterLPC = Math.floor(amtToDetect - lpcForLoop);
var paidLPC = amtToDetect - remainAmtAfterLPC;
if (remainAmtAfterLPC > 0) {
if (remainAmtAfterLPC >= lic_fee_for_loop) {
var remainBalanceAfterLicFee = remainAmtAfterLPC - lic_fee_for_loop
var paidLicFee = remainAmtAfterLPC - remainBalanceAfterLicFee;
var total_amt_payment = Math.floor(paidLicFee + lpcForLoop);
//for balance entry
var bal_lic_fee = Math.floor(lic_fee_for_loop - paidLicFee);
var bal_LPC = Math.floor(lpcForLoop - lpcForLoop);
var bal_total_amt = Math.floor(bal_lic_fee + bal_LPC);
}
}
}
//console.log('demand in for loop',demandInsertData);
let difference = paymentDate - lic_fee_due_date;
var daysDifference = Math.floor(difference / 1000 / 60 / 60 / 24);
var onlineLPC = Math.floor(lic_fee * 0.18 * daysDifference / 365);
var currentLPC = Math.floor(onlineLPC + bal_LPC);
var total_amt = Math.floor(lic_fee + currentLPC);
console.log('in end for loop');
i.lpc = onlineLPC;
i.lic_fee = lic_fee - i.lic_fee;
console.log('in end for loop lic fee', i.lic_fee);
i.lpdays = daysDifference;
i.total_amt = total_amt;
received_amt = remainBalanceAfterLicFee;
console.log('in end for loop received_amt', received_amt);
}
In the above for loop, I want to replace some elements from lastBal array.
At the end of the for loop, I tried to replace some elements as follows :
i.lic_fee = lic_fee - i.lic_fee;
However, values are not being replaced during the next iteration. Instead, old values are being assigned.
How can I find the issue here?
Edit
After changing elements values I want to use them in same for loop.
Means after 1st iteration in for loop I want to change the values of element and use the updated values in next iteration.
Here at end of loop values are updated, but in second iteration old values form lastBal are assign.
Edit 2: Added lastBal
last bal [ RowDataPacket {
demand_id: 42,
user_id: 4,
lic_id: 4,
description: 'Balance',
demand_start_date: '2020-07-01',
demand_end_date: '2020-09-30',
demand_fin_year: '2020-2021',
lic_fee: 27000,
form_fee: 0,
lic_fee_due_date: '2020-06-30',
lrc: 0,
srtax: 0,
lpc: 1224,
total_amt: 28224,
outstanding_amt: 28224,
lpdays: 92,
onlinelpc: 1224,
flag: 0,
lic_fee_pay_id: 0,
demand_added_date: '2020-04-28 19:43:14',
payment_date: '0000-00-00 00:00:00' },
RowDataPacket {
demand_id: 44,
user_id: 4,
lic_id: 4,
description: 'Balance',
demand_start_date: '2020-10-01',
demand_end_date: '2020-12-31',
demand_fin_year: '2020-2021',
lic_fee: 54000,
form_fee: 0,
lic_fee_due_date: '2020-09-30',
lrc: 0,
srtax: 0,
lpc: 1224,
total_amt: 55224,
outstanding_amt: 55224,
lpdays: 0,
onlinelpc: 0,
flag: 0,
lic_fee_pay_id: 0,
demand_added_date: '2020-04-28 19:52:25',
payment_date: '0000-00-00 00:00:00' } ]
Above array is fetch from database.I want to updated 2nd RowDataPacket after 1st iteration in for loop.values to updated 2nd RowDataPacket are dynamic.

Well, I did try to reproduce with your code while putting some sample values in the fields wherever necessay and I do see the expected modifications. Hence, you need to clarify where exactly you're not seeing the changes that you're expecting.
var lastBal = [{ lpc: 1, lic_fee: 2, lpdays: 9, onlinelpc: 4, total_amt: 2 }, { lpc: 3, lic_fee: 4, lpdays: 2, onlinelpc: 5, total_amt: 1 }];
var editedValues = {};
for (let i of lastBal) {
if (!(Object.keys(editedValues).length === 0 && editedValues.constructor === Object)) {
i = {...i, ...editedValues} ;
}
var amtToDetect = 5;
console.log('amt to detect', amtToDetect);
var lpcForLoop = i.lpc;
var lic_fee_for_loop = i.lic_fee;
var daysDifference_for_loop = i.lpdays;
var onlineLPC_for_loop = i.onlinelpc;
var total_amt_for_loop = i.total_amt;
console.log('lic fee for loop', i.lic_fee);
if (amtToDetect >= lic_fee_for_loop) {
var remainAmtAfterLPC = Math.floor(amtToDetect - lpcForLoop);
var paidLPC = amtToDetect - remainAmtAfterLPC;
if (remainAmtAfterLPC > 0) {
if (remainAmtAfterLPC >= lic_fee_for_loop) {
var remainBalanceAfterLicFee = remainAmtAfterLPC - lic_fee_for_loop
var paidLicFee = remainAmtAfterLPC - remainBalanceAfterLicFee;
var total_amt_payment = Math.floor(paidLicFee + lpcForLoop);
//for balance entry
var bal_lic_fee = Math.floor(lic_fee_for_loop - paidLicFee);
var bal_LPC = Math.floor(lpcForLoop - lpcForLoop);
var bal_total_amt = Math.floor(bal_lic_fee + bal_LPC);
}
}
}
//console.log('demand in for loop',demandInsertData);
var daysDifference = 5000;
var onlineLPC = 2000;
var currentLPC = 1000;
var total_amt = 1500;
console.log('in end for loop');
i.lpc = onlineLPC;
i.lic_fee = 4000 - i.lic_fee;
console.log('in end for loop lic fee', i.lic_fee);
i.lpdays = daysDifference;
i.total_amt = 7000;
received_amt = 11000;
console.log('in end for loop received_amt', received_amt);
editedValues = {
pc: onlineLPC,
lic_fee: lic_fee - i.lic_fee,
lpdays: daysDifference,
total_amt: total_amt,
onlinelpc: onlineLPC,
received_amt: remainBalanceAfterLicFee
} // Whatever values you'd like to retain for the subsequent execution
}
console.log(lastBal);
EDIT
- Updated accordingly as you updated your requirements.

Because you are not accessing the array index/key, or in this case the object in javascript.
Take a look at the code below, I can't change "b to bb" assigning "bb" to the variable display the value in the for loop (key). In this case key='bb' will print the value but it will not change it.
var test = [];
test = ['a','b','c','d','e','f','g','h','i'];
for (let key of test){
if (key == 'b') { key = 'bb'}
console.log(key);
}
test[1] = 'cc';
for (let key of test){
console.log(key);
}
In order to change the value in the object/array you need to reference the index/key from the original array. test[1]='cc'; then the value will be changed.
Run the code commenting the test[1]='cc'; line, you will see that the value was not change in the initial loop, then run it uncommenting the line.

Related

Javascript dynamic variable name in loop [duplicate]

This question already has answers here:
How do I create dynamic variable names inside a loop?
(8 answers)
Closed 3 months ago.
I can't figure out how to use dynamic variable in JS.. I have a list of ticker, some balances associated, and I want to display each 'balance sticker' in my loop, dynamically.
But it seems like it's not using the append I add to the variable at all?
var ticker = [CURRENCY1,CURRENCY2,CURRENCY3];
var balancesCURRENCY1 = 20;
var balancesCURRENCY2 = 30;
var balancesCURRENCY3 = 40;
for (var tick in ticker) {
if (('balances'+ticker[tick]) != 0) {
console.log(true);
}
}
To use dynmamic variables, keep the variableNames in an Object, whenever you create the variable name dynamically, refer the object to get the variable's value.
var ticker = ['CURRENCY1','CURRENCY2','CURRENCY3'];
var allBalances = {
balancesCURRENCY1 : 20,
balancesCURRENCY2 : 30,
balancesCURRENCY3 : 40
}
for (var tick in ticker) {
if (allBalances['balances'+ticker[tick]] != 0) {
console.log(true);
}
}
First of all you have to quote names in the array: [CURRENCY1,CURRENCY2,CURRENCY3], otherwise they would be handled as variables.
Then you can access your dynamic names from this see the snippet below:
var ticker = ['CURRENCY1', 'CURRENCY2', 'CURRENCY3'];
var balancesCURRENCY1 = 20;
var balancesCURRENCY2 = 30;
var balancesCURRENCY3 = 40;
for (var tick in ticker) {
if (this['balances'+ticker[tick]] != 0) {
console.log(
ticker[tick],
'balances'+ticker[tick] + ' = ' + this['balances'+ticker[tick]],
true
);
}
}
It would be cleaner to maintain 2 parallel arrays
var ticker = ['CURRENCY1','CURRENCY2','CURRENCY3'];
var balances = [20, 30, 40];
or an array of objects:
var tickerInfo = [
{currency: 'CURRENCY1', balance: 20},
{currency: 'CURRENCY2', balance: 30},
{currency: 'CURRENCY3', balance: 40},
];

Assign circular array to object

I'm a fresher to java-script. I created a object and with key value pairs. Newly I need to add another key (color) with value which should be from color array (color[]). If the object size is greater than color array size, then the value for the color key should be assigned from beginning of color array
var sumArray=[{"sum":1},{"sum":2},{"sum":3},{"sum":4},{"sum":5},{"sum":6}]
var color=["#FF0F00","#FF6600","#FF9E01"];
var combinedObj =sumArray.map(function(obj) {
var me = Object.assign({}, obj);
var i=0;
me.color = color[i++];
return me;
});
Output is
[{"sum":1,"color":"#FF0F00"},{"sum":2,"color":"#FF0F00"},
{"sum":3,"color":"#FF0F00"},{"sum":4,"color":"#FF0F00"},
{"sum":5,"color":"#FF0F00"},{"sum":6,"color":"#FF0F00"}]
Expected Output is
[{"sum":1,"color":"#FF0F00"},{"sum":2,"color":"#FF6600"},
{"sum":3,"color":"#FF9E01"},{"sum":4,"color":"#FF0F00"},
{"sum":5,"color":"#FF6600"},{"sum":6,"color":"#FF9E01"}]
The value is circulating from the beginning if the object size is greater than color array size.
I tried my best by referring. But failed. Thanks in advance
You want to define the iterator outside the loop, and reset it to zero, when it gets to the smallest arrays length
var sumArray = [{"sum": 1}, {"sum": 2}, {"sum": 3}, {"sum": 4}, {"sum": 5}, {"sum": 6}]
var color = ["#FF0F00", "#FF6600", "#FF9E01"];
var i = 0;
var combinedObj = sumArray.map(function(obj) {
var me = Object.assign({}, obj);
i = i === color.length ? 0 : i;
me.color = color[i++];
return me;
});
console.log( JSON.stringify( combinedObj, 0, 4 ) )
You could just reduce the array instead
var sumArray = [{"sum":1},{"sum":2},{"sum":3},{"sum":4},{"sum":5},{"sum":6}]
var color = ["#FF0F00","#FF6600","#FF9E01"];
var combinedObj = sumArray.reduce( (a,b,i) =>
(a.push(Object.assign({}, b, {color:color[i%color.length]})), a)
, []);
console.log( JSON.stringify(combinedObj, 0, 4) )
Your issue is in this line:
var i=0;
move it out of the loop, and in the loop the increment must be:
i = (i + 1) % color.length;
var sumArray=[{"sum":1},{"sum":2},{"sum":3},{"sum":4},{"sum":5},{"sum":6}]
var color=["#FF0F00","#FF6600","#FF9E01"];
var i=0;
var combinedObj = sumArray.map(function(obj) {
var me = Object.assign({}, obj);
me.color = color[i];
i = (i + 1) % color.length;
return me;
});
console.log(combinedObj);
A different approach, avoiding global variables, can be based on second map parameter:
var sumArray=[{"sum":1},{"sum":2},{"sum":3},{"sum":4},{"sum":5},{"sum":6}]
var color=["#FF0F00","#FF6600","#FF9E01"];
var combinedObj = sumArray.map(function(obj, idx) {
var me = Object.assign({}, obj);
me.color = color[idx % color.length];
return me;
});
console.log(combinedObj);
Just check if i value is 3, then assign it back to 0
var sumArray = [{
"sum": 1
}, {
"sum": 2
}, {
"sum": 3
}, {
"sum": 4
}, {
"sum": 5
}, {
"sum": 6
}]
var color = ["#FF0F00", "#FF6600", "#FF9E01"];
var i = 0;
var combinedObj = sumArray.map(function(obj) {
obj.color = color[i];
i++;
if (i === 3) {
i = 0;
}
return obj
}, {});
console.log(combinedObj)

Using array as passing argument in javascript

var chessboard = [[2,1,0],[2,1,0],[0,0,0]];
function checkwins(array){}//The function is too long.I will explain here.It decides
//whether there is a winner.If there is a winner it will return 1 or 0
//(1 stand for number 2's win on the chessboard 0 stands for number 1's win)If there is no winner, it will return 2)
function score(board,depth){
if(checkwins(board)===0)return depth-10;
if(checkwins(board)==1)return 10-depth;
else return 0;
}
function count_move(board,depth,current_turn){
board = board.slice();
var possible_moves = possible_movements(board);
if(checkwins(board)!=2|| possible_moves.length===0)return score(board,depth);
var move_score;
var new_board;
depth++;
if(current_turn===0)move_score = -1000;
else move_score = 1000;
if(!current_turn){
possible_moves.forEach(function(possible_location){
var new_board = board.slice();
new_board[possible_location[0]][possible_location[1]] = 1;
var current_score = count_move(new_board,depth,1);
if(current_score > move_score)move_score = current_score;
});
}else{
possible_moves.forEach(function(possible_location){
var new_board = board.slice();
new_board[possible_location[0]][possible_location[1]] = 2;
var current_score = count_move(new_board,depth,0);
if(current_score < move_score)move_score = current_score;
});
}
return move_score;
}
function ai(board){
var possible_moves = possible_movements(board);
var best_move;
var move_score = -1000;
var current_score ;
possible_moves.forEach(function(move){
var next_board = board.slice();
next_board[move[0]][move[1]] = 1;
current_score = count_move(next_board,0,1);
console.log("Current Move :"+move+"\nCurrent Score :"+current_score+'\nCurrent Board :'+next_board+'\n');
if(current_score > move_score){
move_score = current_score;
best_move = move;
}
});
console.log(best_move);
}
console.log(chessboard);
ai(chessboard);
console.log(chessboard);
I am writing a Tic tac toe game Ai by using Minimax algorithm.I currently have some problems with javascript.I found that when I passed array as argument into function and then revise it in the function.It will change the array passing even outside the function.The console results is below:
[ [ 2, 1, 0 ], [ 2, 1, 0 ], [ 0, 0, 0 ] ]
Current Move :0,2
Current Score :-8
Current Board :2,1,1,2,1,2,2,2,2
Current Move :1,2
Current Score :10
Current Board :2,1,1,2,1,1,2,2,2
Current Move :2,0
Current Score :-10
Current Board :2,1,1,2,1,1,1,2,2
Current Move :2,1
Current Score :-10
Current Board :2,1,1,2,1,1,1,1,2
Current Move :2,2
Current Score :-10
Current Board :2,1,1,2,1,1,1,1,1
[ 1, 2 ]
[ [ 2, 1, 1 ], [ 2, 1, 1 ], [ 1, 1, 1 ] ]
Then I found it seems to use
new_array = array.slice()
inside the function should avoid it, so I add it in my function.The results still don't change.I get quite confused here.
slice performs a shallow copy of an array. That means that the array itself is copied but not any of the objects inside of it.
var a = [ [1], [2], [3] ];
var b = a.slice();
b.push(4);
// Change b does not change a
console.log('A:', JSON.stringify(a));
console.log('B:', JSON.stringify(b));
console.log('');
// However, changing the internal arrays will affect both
b[0][0] = 10;
console.log('A:', JSON.stringify(a));
console.log('B:', JSON.stringify(b));
console.log('');
You need to perform a deep copy, meaning you copy not just the outer array but also the inner arrays.
function copy2DArray(array) {
var copy = [];
array.forEach(function(subArray) {
var copiedSubArray = subArray.slice();
copy.push(copiedSubArray);
});
return copy;
}
var a = [ [1], [2], [3] ];
var b = copy2DArray(a);
// Now you won't change a by modifying b
b[0][0] = 10;
console.log('A:', JSON.stringify(a));
console.log('B:', JSON.stringify(b));

array.push only the last variable in a for loop javascript

i'm actually asking myself why the following code is not working properly i found the solution but it's a bit tricky and i don't like this solution
Here is the code and the problem:
function powerSet( list ){
var set = [],
listSize = list.length,
combinationsCount = (1 << listSize),
combination;
for (var i = 1; i < combinationsCount ; i++ ){
var combination = [];
for (var j=0;j<listSize;j++){
if ((i & (1 << j))){
combination.push(list[j]);
}
}
set.push(combination);
}
return set;
}
function getDataChartSpe(map) {
var res = {};
for (var i in map) {
console.log("\n\n");
var dataSpe = {certif: false,
experience: 0,
expert: false,
grade: 1,
last: 100,
name: undefined
};
var compMatchList = [];
for (var j in map[i].comps_match) {
var tmp = map[i].comps_match[j];
compMatchList.push(tmp.name)
}
var tmpList = powerSet(compMatchList);
var lol = [];
lol.push(map[i].comps_match);
for (elem in tmpList) {
console.log("mdr elem === " + elem + " tmplist === " + tmpList);
var tmp = tmpList[elem];
dataSpe.name = tmpList[elem].join(" ");
lol[0].push(dataSpe);
}
console.log(lol);
}
return res;
}
now here is the still the same code but working well :
function powerSet( list ){
var set = [],
listSize = list.length,
combinationsCount = (1 << listSize),
combination;
for (var i = 1; i < combinationsCount ; i++ ){
var combination = [];
for (var j=0;j<listSize;j++){
if ((i & (1 << j))){
combination.push(list[j]);
}
}
set.push(combination);
}
return set;
}
function getDataChartSpe(map) {
var res = {};
var mapBis = JSON.parse(JSON.stringify(map));
for (var i in map) {
var compMatchList = [];
for (var j in map[i].comps_match) {
var tmp = map[i].comps_match[j];
compMatchList.push(tmp.name)
}
var tmpList = powerSet(compMatchList);
mapBis[i].comps_match = [];
for (elem in tmpList) {
tmpList[elem].sort();
mapBis[i].comps_match.push({certif: false,
experience: 0,
expert: false,
grade: 1,
last: 100,
name: tmpList[elem].join(", ")});
}
}
return mapBis;
}
Actually it's a bit disapointig for me because it's exactly the same but the 1st one doesn't work and the second one is working.
so if anyone can help me to understand what i'm doing wrong it'll be with pleasure
ps: i'm sorry if my english is a bit broken
In the first version, you build one dataSpe object and re-use it over and over again. Each time this runs:
lol[0].push(dataSpe);
you're pushing a reference to the same single object onto the array.
The second version of the function works because it builds a new object each time:
mapBis[i].comps_match.push({certif: false,
experience: 0,
expert: false,
grade: 1,
last: 100,
name: tmpList[elem].join(", ")});
That object literal passed to .push() will create a new, distinct object each time that code runs.

Algorithm for finding overlapping events/times

While working on custom calendar, I can't figure out how to find time slots that overlaps any other time slot.
Time slots start from 0 to 720 (9am to 9pm with each pixel representing a minute).
var events = [
{id : 1, start : 0, end : 40}, // an event from 9:00am to 9:40am
{id : 2, start : 30, end : 150}, // an event from 9:30am to 11:30am
{id : 3, start : 20, end : 180}, // an event from 9:20am to 12:00am
{id : 4, start : 200, end : 230}, // an event from 12:20pm to 12:30pm
{id : 5, start : 540, end : 600}, // an event from 6pm to 7pm
{id : 6, start : 560, end : 620} // an event from 6:20pm to 7:20pm
];
Each time slots is of one hour, for example 9 to 10, 10 to 11, 11 to 12 and so on.
In the above example, three events (id: 1,2,3) are overlapping for the 9-10 start time: 9:00, 9:30 and 9:20. And other events overlapping are int time slot of 6 to 7 (id: 5, 6) with 6 and 6:20 start times. The event with id 4 doesn't have any overlapping events in the time slot of 12 to 1.
I am looking for a way to get all overlapping event ids as well as number of events in a particular time slot, this is expected output:
[
{id:1, eventCount: 3},
{id:2, eventCount: 3},
{id:3, eventCount: 3},
{id:5, eventCount: 2},
{id:6, eventCount: 2}
]
For ids (1 to 3), there are 3 events for time slot 9 to 10 and 2 events for time slot 6 to 7.
I have created this formula to convert time number to actual time:
var start_time = new Date(0, 0, 0, Math.abs(events[i].start / 60) + 9, Math.abs(events[i].start % 60)).toLocaleTimeString(),
var end_time = new Date(0, 0, 0, Math.abs(events[i].end / 60) + 9, Math.abs(events[i].end % 60)).toLocaleTimeString();
This is what I have so far:
function getOverlaps(events) {
// sort events
events.sort(function(a,b){return a.start - b.start;});
for (var i = 0, l = events.length; i < l; i++) {
// cant figure out what should be next
}
}
DEMO if you need.
from my jquery-week-calendar commit, this is how i do it:
_groupOverlappingEventElements: function($weekDay) {
var $events = $weekDay.find('.wc-cal-event:visible');
var complexEvents = jQuery.map($events, function (element, index) {
var $event = $(element);
var position = $event.position();
var height = $event.height();
var calEvent = $event.data('calEvent');
var complexEvent = {
'event': $event,
'calEvent': calEvent,
'top': position.top,
'bottom': position.top + height
};
return complexEvent;
}).sort(function (a, b) {
var result = a.top - b.top;
if (result) {
return result;
}
return a.bottom - b.bottom;
});
var groups = new Array();
var currentGroup;
var lastBottom = -1;
jQuery.each(complexEvents, function (index, element) {
var complexEvent = element;
var $event = complexEvent.event;
var top = complexEvent.top;
var bottom = complexEvent.bottom;
if (!currentGroup || lastBottom < top) {
currentGroup = new Array();
groups.push(currentGroup);
}
currentGroup.push($event);
lastBottom = Math.max(lastBottom, bottom);
});
return groups;
}
there's a bit of component-specific noise around, but you'll get the logic:
sort the events by their starting ascending
sort the events by their ending ascending
iterate over the sorted events and check the starting/ending of the previous event (done rather by position, than by the event properties themself - just because the design might overlap, but the events not ... eg: making a border 2px, events with not overlapping start/end-times might overlap or "touch")
each overlapping-group (currentGroup) is a new array inside the groups-array
soo ... your code might look sth alike this (btw, no need to work with the real date-instances)
events.sort(function (a, b) {
var result = a.start - b.start;
if (result) {
return result;
}
return a.end - b.end;
});
var groups = new Array();
var currentGroup;
var lastEnd = -1;
jQuery.each(events, function (index, element) {
var event = element;
var start = event.start;
var end = event.end;
if (!currentGroup || lastEnd < start) {
currentGroup = new Array();
groups.push(currentGroup);
}
currentGroup.push(event);
lastEnd = Math.max(lastEnd, end);
});
return groups;
soo ... you are not willed to push some own energy into your problem ... well
var output = new Array();
jQuery.each(groups, function (index, element) {
var group = element;
if (group.length <= 1) {
return;
}
jQuery.each(group, function (index, element) {
var event = element;
var foo = {
'id': event.id,
'eventCount': group.length
};
output.push(foo);
});
});
To me it is easier to use timestamps for each start and end event, that way you can work with them directly or change them to date objects. To get the value, create a date object for each start and end, then:
var a.start = startDate.getTime();
var a.end = endDate.getTime();
For overlap:
if (a.start <= b.start && a.end > b.start ||
a.start < b.end && a.end >= b.end) {
// a overlaps b
}
You can leave them as date objects if you like, the above will work just as well.
Edit
Ok here's a working example:
Assuming a nominal date of 2012-05-15, then the events array looks like:
// Use iso8601 like datestring to make a local date object
function getDateObj(s) {
var bits = s.split(/[- :]/);
var date = new Date(bits[0], bits[1] - 1, bits[2]);
date.setHours(bits[3], bits[4], 0);
return date;
}
var events = [
{id: 1, start: getDateObj('2012-05-15 09:00'), end: getDateObj('2012-05-15 09:30')},
{id: 2, start: getDateObj('2012-05-15 09:30'), end: getDateObj('2012-05-15 11:30')},
{id: 3, start: getDateObj('2012-05-15 09:20'), end: getDateObj('2012-05-15 12:00')},
{id: 4, start: getDateObj('2012-05-15 12:20'), end: getDateObj('2012-05-15 12:30')},
{id: 5, start: getDateObj('2012-05-15 18:00'), end: getDateObj('2012-05-15 19:00')},
{id: 6, start: getDateObj('2012-05-15 18:20'), end: getDateObj('2012-05-15 19:20')}
];
function getOverlappingEvents(eventArray) {
var result = [];
var a, b;
// Sort the event array on start time
eventArray.sort(function(a, b) {
return a.start - b.start;
});
// Get overlapping events
for (var i=0, iLen=eventArray.length - 1; i<iLen; i++) {
a = eventArray[i];
b = eventArray[i + 1];
if ((a.start <= b.start && a.end > b.start) ||
(a.start < b.end && a.end >= b.end) ) {
result.push([a.id, b.id]);
}
}
return result;
}
// Run it
alert(getOverlappingEvents(events).join('\n')); // 1,3 2,3 5,6
Here's code that will do what you want. As others have mentioned you'd probably be better served by storing date objects, but that's a different issue.
function getOverlaps(events) {
// sort events
events.sort(function (a, b) {
return a.start - b.start;
});
var results = [];
for (var i = 0, l = events.length; i < l; i++) {
var oEvent = events[i];
var nOverlaps = 0;
for (var j = 0; j < l; j++) {
var oCompareEvent = events[j];
if (oCompareEvent.start <= oEvent.end && oCompareEvent.end > oEvent.start || oCompareEvent.end <= oEvent.start && oCompareEvent.start > oEvent.end) {
nOverlaps++;
}
}
if (nOverlaps > 1) {
results.push({
id: oEvent.id,
eventCount: nOverlaps,
toString: function () {
return "[id:" + this.id + ", events:" + this.eventCount + "]"
}
});
}
}
return results;
}

Categories

Resources