Count distinct elements in array - javascript

I have data that comes from my server to datatables.
I'm successfully populating my table but in footer callback I want to do some statistics.
Lets say I have data like so:
var data = [{
date: '2013-05-12',
holiday: "One type of holiday",
dayType: "Weekend"
}, {
date: '2013-05-13',
holiday: "Another type",
dayType: "Weekend"
}, {
date: '2013-05-14',
holiday: "Another type",
dayType: "Work"
}, {
date: '2013-05-15',
holiday: "",
dayType: "Work"
}];
I would like to count number of days with different holidays.
Here is result I would like to get:
var summary= [
{
"One type of holiday": {
"work": 0,
"weekend": 1
}
},
{
"Another type": {
"work": 1,
"weekend": 1
}
}];
I've created a very simple code to simply aggregate holidays:
for (var i = 0; i < data.length; i++) {
//console.log(data[i].holiday);
/*other stuff here*/
if (data[i].holiday.length > 0)
summary[data[i].holiday] = summary[data[i].holiday] + 1 || 1;
}
but this gives me invalid results, because in my data array holiday contains spaces.
I need a way to fix this and to split holidays based on dayType.
MY SOLUTION:
My version of answer:
var summary = {}, d, tmp, type;
for (var i = 0; i < data.length; i++) {
var d = data[i];
if (d.holiday.length > 0) {
type = d.dayType == 'Weekend' || d.dayType == 'Free' ? 'Weekend' : 'Work';
tmp = summary[d.holiday];
if (!tmp) {
tmp = {
Weekend: 0,
Work: 0
};
summary[d.holiday] = tmp;
}
summary[d.holiday][type] += 1;
}
}
Because this is modified version of #Arun answer I'm not posting this as standalone answer.
I find my version easier to understand, hope someone find's it useful.

Try
var summary = [], summaryMap = {}, d, map, m;
for (var i = 0; i < data.length; i++) {
var d = data[i];
map = summaryMap[d.holiday];
if(!map){
map = {
Work: 0,
Weekend: 0
};
m = {};
m[d.holiday] = map;
summary.push(m);
summaryMap[d.holiday] = map;
}
map[d.dayType] += 1;
}
console.log(summary);
console.log(JSON.stringify(summary));
Demo: Fiddle

go for
console.log(Object.keys(summary).length);
instead of
console.log(summary.length);
Because you can get the number of elements in a js object by using the length attribute.
note: using Object.keys may lead you to browser compatibility issues. As its supported form IE 9 and Firefox 4. See more info in this MDN article.
you can find more info and solutions for this problem in this answer.
see the updated fiddle.

Here's my attempt:
var summary = [];
var holidayTypes = [];
var dayTypes = [];
//first work out the different types of holidays
for (var i = 0; i < data.length; i++) {
if(holidayTypes.indexOf(data[i].holiday) == -1){
//this is a new type of holiday
holidayTypes.push(data[i].holiday);
}
if(dayTypes.indexOf(data[i].dayType) == -1){
//new type of day.
dayTypes.push(data[i].dayType);
}
}
console.log('types of holiday: ' + JSON.stringify(holidayTypes));
console.log('types of day: ' + JSON.stringify(dayTypes));
for(index in holidayTypes){
var typeobj = {};
//create an object for each type of holiday
typeobj[holidayTypes[index]] = {};
for(index2 in dayTypes){
//initialize a count for each type of day
typeobj[holidayTypes[index]][dayTypes[index2]] = 0;
//iterate through the data and count the occurrences where the day AND holiday match.
//if they do, iterate the value.
for (var j = 0; j < data.length; j++){
if((data[j].holiday == holidayTypes[index])
&& (data[j].dayType == dayTypes[index2])){
typeobj[holidayTypes[index]][dayTypes[index2]]++;
}
}
}
summary.push(typeobj);
}
console.log(JSON.stringify(summary));
Fiddle here
Output:
[{"One type of holiday":{"Weekend":1,"Work":0}},{"Another type":{"Weekend":1,"Work":1}},{"":{"Weekend":0,"Work":1}}]
It works but is unlikely to be as efficient as the guys above!

Related

For each entry in a sub array add values

let b = [];
this.state.sidejobs.forEach((user) => {
console.log(user);
if (!b.hasOwnProperty(user.jobworker)) b[user.jobworker] = 0;
b[user.jobworker] += user.duration;
});
One entry in jobworker has an array with two ids... how do i split it and add the duration respectively.
Name ID Total Hours
Mike Smith 281 5
284,281 5
John Doe 284 21
Chris Smith 283 23
let b = [];
this.state.sidejobs.forEach((user) => {
var jobworkers = user.jobworker.toString().split(",");
for (var i = 0; i < jobworkers.length; i++) {
var worker = jobworkers[i].trim();
if (!b.hasOwnProperty(worker)) b[worker] = 0;
b[worker] += user.duration;
}
});
First of all, is b an array or an object? Or are you using it as both? I suspect you meant for it to be an anonymous object.
let b = {};
Secondly, it would really help to know the exact structure of user.jobworker (eg: call "JSON.stringify(user.jobworker)"). For now, I will assume that the structure of the user object is as follows:
{
name: "Mike Smith",
id: 281,
duration: 5,
jobworker: [284, 281]
}
If that is the case, all you have to do is
let b = {};
this.state.sidejobs.forEach((user) => {
for (var i = 0; i < user.jobworker.length; i++) {
if (!b.hasOwnProperty(user.jobworker[i])) b[user.jobworker[i]] = 0;
b[user.jobworker[i]] += user.duration;
}
});
If instead user.jobworker contains a comma-delimited string of ids (eg: user.jobworker = "284,281") then you will have to split the string first:
this.state.sidejobs.forEach((user) => {
var jobworkers = user.jobworker.split(",");
for (var i = 0; i < jobworkers.length; i++) {
var worker = jobworkers[i].trim();
if (!b.hasOwnProperty(worker)) b[worker] = 0;
b[worker] += user.duration;
}
});

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.

Comparing an Array with an Objects' Array in JavaScript

I am new to JavaScript and wondering how can I compare an array with another array consists of JavaScript objects.
The array is a series of sorted time in the "YYYY-MM-DD" format.
The array of objects missed some price values of several days.
I want to find the missed value and assign it as "NULL".
For example, I have an array as:
array = ['2014-10-09','2014-10-10','2014-10-11','2014-10-12'];
and an array with objects as:
objArray = [{
date:"2014-10-09",
price:"100"
},
{
date:"2014-10-10",
price:"99"
},
{
date:"2014-10-12",
price:"102"
}];
I want to get the price array in this way:
priceResult = [100, 99, "NULL", 102];
What would be the most efficient way without using other libraries? I wanted to see if anyone had a more elegant solution. I deeply appreciate your help.
You can create a lookup set from the object array, then you can use that to translate the dates to prices.
This scales well, as it is an O(n+m) solution rather than the O(n*m) solution that you get if you use a loop in a loop to find the prices.
var array = ['2014-10-09','2014-10-10','2014-10-11','2014-10-12'];
var objArray = [{ date:"2014-10-09", model:"A", price:"100" },{ date:"2014-10-10", model:"A", price:"99" },{ date:"2014-10-12", model:"A", price:"102" }];
var lookup = {};
for (var i = 0; i < objArray.length; i++) {
lookup[objArray[i].date] = parseInt(objArray[i].price, 10);
}
var priceResult = [];
for (var i = 0; i < array.length; i++) {
if (lookup.hasOwnProperty(array[i])) {
priceResult.push(lookup[array[i]]);
} else {
priceResult.push('NULL');
}
}
// output result in StackOverflow snippet
document.write(JSON.stringify(priceResult));
Note: Instead of the string 'NULL' you might want to use the value null instead, as it is generally easier to handle.
lodash is the best library for this. But you did say "without using other libraries", so you will need to do it natively.
The easiest way to do it is nested for loops:
var i, j, d, res = [];
for (i=0; i<dateArray.length; i++) {
d = dateArray[i];
for (j=0; j<objArray.length; j++) {
if (objArray[j] && objArray[j].date && objArray[j].date === d) {
res.push(objArray[j].price);
j = objArray.length; // don't waste energy searching any more, since we found it
}
}
}
// res now contains all you wanted
If objArray is really big, and you don't want to search it multiple times, then you could turn it into an object indexed by date:
var i, obj = {}, d, res = [];
for (i=0; i<objArray.length; i++) {
if (objArray[i] && objArray[i].date) {
obj[objArray[i].date] = objArray[i];
}
}
for (i=0; i<dateArray.length; i++) {
d = dateArray[i];
res.push(obj[d] ? obj[d].price : null : null);
}
// res now contains all you wanted
Loop trough the object and search for the date in your array
// Add contains to array proto: http://css-tricks.com/snippets/javascript/javascript-array-contains/
var priceResult = [];
for(var i in objArray) {
if(dateArray.contains(objArray[i].date)) priceResult.push(objArray[i].date));
}
console.log('matches:', priceResult);
This function will give you map of all individual arrays in your object array
function getArrayMap(array) {
var map={}
for(var i=0;i<array.length;i++){
var o = array[i];
for(var k in o){
if(!map[k]){
map[k]=[];
}
map[k].push(o[k]);
}
}
return map;
}
you can use it like -
var map = getArrayMap(objArray);
console.log(map["date"]);//date array
console.log(map["price"]);//price array
console.log(map["model"]);//model array
If i am understanding your question correctly, for all the values in array, you want to check the objArr and find the price for each date, and if not found u want to inset null. If this is what you want, then following will help
var found= false;
var list=[];
for(var i=0; i< dateArray.length; i++)
{
for(var j=0; j< objArray.length; j++)
{
if(objArray[j].date == dateArray[i])
{
list.push(objArray[j].price);
found = true;
}
}
if(!found)
{
list.push("null");
}
found = false;
}
alert(list);
(I'm going to call your first array dates rather than array, to avoid confusion.)
There are basically two options:
Loop through your dates array and, for each entry, loop through the objArray looking for a match, and when found add to your priceResult array, or
Build a map from your objArray, then loop through yourdatesarray once, building thepriceResult` array.
Looping and Looping
You can loop through your dates array using forEach, and you can use Array#some to find out whether your objArray contains the date and add to priceResult if so (it's an ES5 feature, but you can polyfill it for really old browsers):
var priceResult = [];
dates.forEach(function(date) {
objArray.some(function(object) {
if (object.date == date) {
priceResult.push(object.price);
return true;
}
});
});
Array#some keeps looping until you return true, which is why we do that when we find the firs tmatch. That's why I say this is "looping and looping," even though we only write one loop, the other is within Array#some.
var dates = ['2014-10-09', '2014-10-10', '2014-10-11', '2014-10-12'];
var objArray = [
{
date: "2014-10-09",
model: "A",
price: "100"
},
{
date: "2014-10-10",
model: "A",
price: "99"
},
{
date: "2014-10-12",
model: "A",
price: "102"
}
];
// Do it
var priceResult = [];
dates.forEach(function(date) {
objArray.some(function(object) {
if (object.date == date) {
priceResult.push(object.price);
return true;
}
});
});
snippet.log(priceResult.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Mapping and Looping
First, create a map of prices by date:
var prices = {};
objArray.forEach(function(object) {
prices[object.date] = object.price;
});
...then create your results:
var priceResult = [];
dates.forEach(function(date) {
if (prices.hasOwnProperty(date)) {
priceResult.push(prices[date]);
}
});
var dates = ['2014-10-09', '2014-10-10', '2014-10-11', '2014-10-12'];
var objArray = [
{
date: "2014-10-09",
model: "A",
price: "100"
},
{
date: "2014-10-10",
model: "A",
price: "99"
},
{
date: "2014-10-12",
model: "A",
price: "102"
}
];
// Create the map
var prices = {};
objArray.forEach(function(object) {
prices[object.date] = object.price;
});
// Create your results:
var priceResult = [];
dates.forEach(function(date) {
if (prices.hasOwnProperty(date)) {
priceResult.push(prices[date]);
}
});
// Show them
snippet.log(priceResult.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
var dates = ['2014-10-09','2014-10-10','2014-10-11','2014-10-12'];
var objArray = [{date:"2014-10-09", model:"A", price:"100" }, {date:"2014-10-10", model:"A", price:"99" }, {date:"2014-10-12", model:"A", price:"102" }];
var val;
var priceResult = [];
for (var a in dates) {
val = null;
for (var b in objArray) {
if (dates[a] == objArray[b].date) {
val = objArray[b].price;
}
}
priceResult.push(val);
}
var dates = ['2014-10-09', '2014-10-10', '2014-10-11', '2014-10-12'];
var objArray = [{
date: "2014-10-09",
model: "A",
price: "100"
}, {
date: "2014-10-10",
model: "A",
price: "99"
}, {
date: "2014-10-12",
model: "A",
price: "102"
}];
var val;
var priceResult = [];
for (var a in dates) {
val = null;
for (var b in objArray) {
if (dates[a] == objArray[b].date) {
val = objArray[b].price;
}
}
priceResult.push(val);
}
// output result in StackOverflow snippet
document.write(JSON.stringify(priceResult));
Try this:
var temp[]
temp= jQuery.grep(objArray , function (n, i)
{
for(j=0;j<dateArray.lenght+j++ )
if( n.date === dateArray[j])
return n.price;
);
dateArray = ["2014-10-09", "2014-10-10", "2014-10-11", "2014-10-12"];
function ObjectExample(date1,model,price)
{
this.date1 = date1;
this.model = model;
this.price = price;
}
var objArray = [new ObjectExample("2014-10-09","A","100"), new ObjectExample("2014-10-10","A","99"), new ObjectExample("2014-10-12","A","102")];
var i = 0;
var priceDate = new Array();
var count = 0;
while(i < dateArray.length)
{
var j = 0;
while(j < objArray.length)
{
if(dateArray[i] == objArray[j].date1)
{
priceDate[count] = objArray[j].price;
break;
}
else priceDate[count] = "NULL";
j = j + 1;
}
i = i + 1;
count++;
}
document.write(priceDate);

Joining two collections efficiently?

I have run into an issue where I am trying to join two arrays similar to the ones below:
var participants = [
{id: 1, name: "abe"},
{id:2, name:"joe"}
];
var results = [
[
{question: 6, participantId: 1, answer:"test1"},
{question: 6, participantId: 2, answer:"test2"}
],
[
{question: 7, participantId: 1, answer:"test1"},
{question: 7, participantId: 2, answer:"test2"}
]
];
Using nested loops:
_.each(participants, function(participant) {
var row, rowIndex;
row = [];
var rowIndex = 2
return _.each(results, function(result) {
return _.each(result, function(subResult) {
var data;
data = _.find(subResult, function(part) {
return part.participantId === participant.id;
});
row[rowIndex] = data.answer;
return rowIndex++;
});
});
});
This works ok as long as the arrays are small, but once they get larger I am getting huge performance problems. Is there a faster way to combine two arrays in this way?
This is a slimmed down version of my real dataset/code. Please let me know if anything doesn't make sense.
FYI
My end goal is to create a collection of rows for each participant containing their answers. Something like:
[
["abe","test1","test1"],
["joe","test2","test2"]
]
The perf* is not from the for loops so you can change them to _ iteration if they gross you out
var o = Object.create(null);
for( var i = 0, len = participants.length; i < len; ++i ) {
o[participants[i].id] = [participants[i].name];
}
for( var i = 0, len = results.length; i < len; ++i ) {
var innerResult = results[i];
for( var j = 0, len2 = innerResult.length; j < len2; ++j) {
o[innerResult[j].participantId].push(innerResult[j].answer);
}
}
//The rows are in o but you can get an array of course if you want:
var result = [];
for( var key in o ) {
result.push(o[key]);
}
*Well if _ uses native .forEach then that's easily order of magnitude slower than for loop but still your problem is 4 nested loops right now so you might not even need the additional 10x after fixing that.
Here is a solution using ECMA5 methods
Javascript
var makeRows1 = (function () {
"use strict";
function reduceParticipants(previous, participant) {
previous[participant.id] = [participant.name];
return previous;
}
function reduceResult(previous, subResult) {
previous[subResult.participantId].push(subResult.answer);
return previous;
}
function filterParticipants(participant) {
return participant;
}
return function (participants, results) {
var row = participants.reduce(reduceParticipants, []);
results.forEach(function (result) {
result.reduce(reduceResult, row);
});
return row.filter(filterParticipants);
};
}());
This will not be as fast as using raw for loops, like #Esailija answer, but it's not as slow as you may think. It's certainly faster than using Underscore, like your example or the answer given by #Maroshii
Anyway, here is a jsFiddle of all three answers that demonstrates that they all give the same result. It uses quite a large data set, I don't know it compares to the size you are using. The data is generated with the following:
Javascript
function makeName() {
var text = "",
possible = "abcdefghijklmnopqrstuvwxy",
i;
for (i = 0; i < 5; i += 1) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
var count,
count2,
index,
index2,
participants = [],
results = [];
for (index = 0, count = 1000; index < count; index += 4) {
participants.push({
id: index,
name: makeName()
});
}
for (index = 0, count = 1000; index < count; index += 1) {
results[index] = [];
for (index2 = 0, count2 = participants.length; index2 < count2; index2 += 1) {
results[index].push({
question: index,
participantId: participants[index2].id,
answer: "test" + index
});
}
}
Finally, we have a jsperf that compares these three methods, run on the generated data set.
Haven't tested it with large amounts of data but here's an approach:
var groups = _.groupBy(_.flatten(results),'participantId');
var result =_.reduce(groups,function(memo,group) {
var user = _.find(participants,function(p) { return p.id === group[0].participantId; });
var arr = _.pluck(group,'answer');
arr.unshift(user.name);
memo.push(arr);
return memo ;
},[]);
The amounts of groups would be the amount of arrays that you'll have so then iterating over that with not grow exponentially as if you call _.each(_.each(_.each which can be quite expensive.
Again, should be tested.

need to implement my algorithm using javascript

I have made small algorithm and want to implement it using javascript. Here is my algorithm
I have a data in data.json file in this format
[
"109 200",
"109 201",
"102 202",
"103 202"
]
What I am trying to do is
Create four array containers i.e. c1, c2, c3 and c4.
Put above data in c1 container as it is
loop through c1 and put the data in c4 in following format
"109",
"200",
"109",
"201",
"102",
"202",
"103",
"202"
loop through c1 and put them in c2 in this format
"109,200"
then check if c3 is empty then read first value from c2 and push it in c3.
repeat step 4 but this time put second data i.e. "109 201" from c1 in c2 in this format
"109,201"
then check if c3 is not empty then loop through c2 and check if any of these two values are repeated in c4. If it is repeated then repeat step 6 and 7 until it finds least amount of numbers from data.json.
This algorithm is not efficient but still I want to use this.
Here is my code.
var teams = [],
c1 = [], arr = [], left = [], right = [], j = 0,
show = function () {
var span = $('#list');
$.getJSON('data/data.json', function (ids) {
//c1.push(c);
for (var i = 0; i < ids.length; i++) {
var a = smallcontainer(ids);
var b = bigcontainer(ids);
var c;
if (c1 == "") {
c = a[0].split(" ");
console.log(c);
} else {
}
//console.log(c);
var id = ids[i];
teams = id;
$('<li>' + id + '</li>').appendTo(span);
}
});
},
smallcontainer = function (teams) { //arr
arr = [teams[j]];
j++;
return arr;
},
bigcontainer = function (ids) { //c3. in code it is left+right=result
for (var i = 0; i < ids.length; i++) {
var splitted = ids[i].split(" ");
left.push(splitted[0]);
right.push(splitted[1]);
}
var result = left.concat(right);
};
Update
data inside data.json file has four teams with two members in each team in this form
"109 200" = Team 1
"109 201" = Team 2
"102 202" = Team 3
"103 202" = Team 4
So now I have to compute the smallest number of people and it has to select one member from each team from this list and show their IDs. So the output for above would be
109
202
Latest update
I am still waiting for help
Solution
Here is the solution with the help of AlexBEll and PAEz. I used solution below which was basically solved by AlexBell
var data = [
"1009 2000",
"1009 2001",
"1002 2002",
"1003 2002",
"1004 2003",
"1005 2004",
"1006 2005",
"1007 2006",
"1007 2007",
"1008 2008",
"1009 2008",
"1010 2009",
"1011 2010",
"1012 2010"
];
var first = [], second = [], result = {}, out = '';
//Separe the ids
for(var i = 0; i < data.length; i++){
var el = data[i].split(' ');
first[i] = el[0];
second[i] = el[1];
}
for(var k = 0; k < first.length; k++){
//Count the elements
var nOfFirst = countElemnts(first, first[k]);
var nOfSecond = countElemnts(second, second[k]);
//If the first is in more that second take it
if(nOfFirst > nOfSecond){
result[first[k]] = 0;
//Else take the second
}else if(nOfFirst < nOfSecond){
result[second[k]] = 0;
//If is only one take it
}else{
result[first[k]] = 0;
}
}
function countElemnts(arr, el){
var count = 0;
for(var j = 0; j < arr.length; j++){
if(arr[j] == el)
count++;
}
//console.log(el+' : '+count);
return count;
}
for(var n in result){
out += 'The id n: '+n+' is in the list\n';
}
alert(out);
Does this work?....
var teams=[
"109 200",
"109 201",
"102 202",
"103 202"
];
var members ={};
var matesId='109';
// Members that won
var wins={};
// First lets find out how many teams a member is in
for (var i=0,length=teams.length; i<length;i++){
var temp = teams[i].split(' ');
for (var z=0,zlength=temp.length;z<zlength;z++){
if (!members[temp[z]]) members[temp[z]]={wins:0,totalTeams:0,id:temp[z]};
members[temp[z]].totalTeams=members[temp[z]].totalTeams+1;
}
teams[i]=[members[temp[0]],members[temp[1]]];
}
for (var i=0,length=teams.length; i<length;i++){
var member1=teams[i][0];
var member2=teams[i][1];
if (member1.totalTeams>member2.totalTeams){
member1.wins=member1.wins+1;
} else if (member1.totalTeams<member2.totalTeams){
member2.wins=member2.wins+1;
} else {
member1.wins=member1.wins+1;
member2.wins=member2.wins+1;
}
}
for (var i=0,length=teams.length; i<length;i++){
var member1=teams[i][0];
var member2=teams[i][1];
if (member1.wins>member2.wins){
if (wins[member2.id]!==true) wins[member1.id]=true;
} else if (member1.wins<member2.wins){
if (wins[member1.id]!==true) wins[member2.id]=true;
} else if (!wins[member1.id] && !wins[member2.id]) {
if (member1.id==matesId && member2.id==matesId) {
wins[matesId]=true;
} else{
// A draw, so pick one
Math.round(Math.random())==1 ? wins[member2.id]=true : wins[member1.id]=true;
}
}
}
var keys=Object.keys(wins);
var results=[];
results.push(keys.length);
for (var i=0,length=keys.length; i<length;i++){
results.push(keys[i]);
}
results=results.join('\n');
document.querySelector('#output').innerText=results;​
http://jsfiddle.net/PAEz/dLUqj/3/
EDIT: Updated it so its a little easier to read.
EDIT: Realised you dont need a draw and win, just a win will do.
LAST EDIT: Noticed one small error, it should all be right now.

Categories

Resources