我正在迭代 .csv 文件以在 Angular js 应用程序中进行一些元素级别验证。我在 Angular 中找不到更好的库,所以我开始编写自定义 JavaScript 来处理这种情况。下面是附加的数据示例(对第一列 CN 和第五列 NAME 数据感兴趣)。我能想到的只是几个 if 条件来检查 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 列中找到连续行的相同值,那么我想检查这些行的 NAME 列中是否有重复的值。
- 如果我对于相同 CN 值的不同行(不同行)没有重复的 NAME,那么我不应该抛出错误。
在此数据示例中,我应该在 CN = USA、NAME=Kobe 的第三行捕获异常,其余数据应该可以正常工作
最佳答案
您可以将 key 对 (CN + NAME) 作为串联 key 存储在 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 Map 和 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; }
关于javascript - 检查 JavaScript 和/或 AngularJS 中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939274/