我有2000人的投票数据。每行包含一系列投票,每个投票用于两个选项中的一个(或两者都不)。我正在尝试将这些数据压缩成每个主题的总投票数。
我有CSV file看起来像这样:
A C F
B C E
A D E
第一列是A
和B
之间的投票,C
和D
之间的第二列。
答案 0 :(得分:1)
这应该可以解决问题:
var parse = function (url) {
getCSV(url, function (err, data) {
// split the data by line, then split each line by commas
data = data.split("\n").map(function (line) { return line.split(",") });
// we want to ignore the first two elements since they're junk
var mapping = groupOptions(data[0].slice(2));
// skip the first line, since it isn't a vote
data.slice(1).forEach(function (line) {
// skip the first two elements of each line
// then go through each "vote"
line.slice(2).forEach(function (vote, i) {
// if `mapping[i][0]` (our record of votes) equals `vote`, record it
if (mapping[i][0].name == vote) {
mapping[i][0].number += 1;
// also explicitly check whether the other option was voted for
// since voting is optional
} else if (mapping[i][1].name == vote){
mapping[i][1].number += 1;
}
})
})
console.log(mapping);
return mapping;
});
}
var groupOptions = function (options) {
// this function will be fed an array of strings:
// ["A or B", "C or D", ... ]
// we want to reduce this to a single mapping
return options.reduce(function (p, c) {
// split the current array element at " or " (to get both options)
var holder = c.split(" or ");
// now push an array of two objects, each representing the different options
p.push([{ name: holder[0], number: 0 }, { name: holder[1], number: 0 }]);
return p;
}, []);
}
var getCSV = function (url, done) {
var req = new XMLHttpRequest();
req.open("GET", url);
req.onload = function () { return done(null, req.response); }
req.onerror = function () { return done(req.statusText, req.response); }
req.send();
}
parse("http://www.sfu.ca/~djr7/data/Round3.csv");
它返回以下数据(但是作为对象数组的数组):
/*
Saber (Fate/Stay Night UBW) 1031 Rin (Fate/Stay Night UBW) 658
Akame (Akame ga Kill!) 1282 Ema (Shirobako) 426
Kurumi (Date A Live) 1114 Esdeath (Akame ga Kill!) 602
Tachibana (Nisekoi) 885 Yuuki (Sword Art Online 2) 854
Stephanie (No Game No Life) 903 Tsugumi (Nisekoi) 834
Rikka (Chuunibyou demo Koi ga Shitai! Ren) 0 Sinon (Sword Art Online 2) 1018
*/