我正在迭代.csv文件,在angular js app中进行一些元素级验证。我无法在角度找到更好的库,所以我开始编写自定义的javascript来处理这种情况。下面是附加的数据样本(对第一列CN和第5列NAME数据感兴趣)。如果条件检查i,j的索引并存储值,我所能想到的就是少数。任何建议,将不胜感激。
CN N ACTIVE TYPE NAME NO COM
USA 45 Engin Fed Anderson #10 NA
USA 46 Sports BB Kobe #1 NA
USA 32 Sports Soccer Kobe #17 NA
GER 30 Sports Soccer Gotze #12 NA
GER 27 Sports Soccer Ozil #18 NA
ITA 38 Sports Soccer Buffon #2 NA
代码段
for ( var i=0; i< file.length; i++ ){
var singleRowData = file[i].split(',');
singleRowData = singleRowData.filter(function(n){ return n != "" });
for ( var j=0; j< singleRowData.length; j++){
duplicateFunction(singleRowData, singleRowData[j], j, i);
}
}
function duplicateFunction ( singleRowData, singleRowDataElement, singleRowDataElementIndex, singleRowDataIndex){
/*
handle the duplicates
*/
}
在这个数据示例中,我应该在CN = USA,NAME = Kobe的第3行捕获异常,其余数据应该可以正常工作
答案 0 :(得分:1)
您可以将密钥对(CN + NAME)存储为<em> keys 对象中的连锁密钥,当您在那里找到新记录时,您知道您有重复:
var file = [
'USA,45,Engin,Fed,Anderson,#10,NA',
'USA,46,Sports,BB,Kobe,#1,NA',
'USA,32,Sports,Soccer,Kobe,#17,NA',
'GER,30,Sports,Soccer,Gotze,#12,NA',
'GER,27,Sports,Soccer,Ozil,#18,NA',
'ITA,38,Sports,Soccer,Buffon,#2,NA'
];
var keys = {}; // store the keys that you have processed
var result = []; // array with accepted rows
for ( var i=0; i< file.length; i++ ){
var singleRowData = file[i].split(',');
singleRowData = singleRowData.filter(function(n){ return n != "" });
var key = singleRowData[0] + '|' + singleRowData[4]; // CN + NAME
if (key in keys) {
console.log("Duplicate at " + i + " is ignored");
} else {
keys[key] = 1; // register key
result.push(singleRowData);
}
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这是一个相同构思的更紧凑的ES6版本,但带有ES6地图和reduce
:
const file = [
'USA,45,Engin,Fed,Anderson,#10,NA',
'USA,46,Sports,BB,Kobe,#1,NA',
'USA,32,Sports,Soccer,Kobe,#17,NA',
'GER,30,Sports,Soccer,Gotze,#12,NA',
'GER,27,Sports,Soccer,Ozil,#18,NA',
'ITA,38,Sports,Soccer,Buffon,#2,NA'
];
const result = [...file.reduce( (result, line) => {
const singleRowData = line.split(',').filter(n => n != ""),
key = singleRowData[0] + '|' + singleRowData[4]; // CN + NAME
return result.has(key) ? result : result.set(key, singleRowData);
}, new Map).values()];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }