检查javascripts和/或angularjs中的重复项

时间:2017-03-21 22:22:19

标签: javascript angularjs arrays multidimensional-array

我正在迭代.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
*/
}
  1. 如果我在CN列中找到连续行的相同值,那么我想检查这些行的NAME列中是否有重复值。
  2. 如果我没有为相同CN值(不同行)的不同行重复NAME,那么我就不应该抛出错误。
  3. 在这个数据示例中,我应该在CN = USA,NAME = Kobe的第3行捕获异常,其余数据应该可以正常工作

1 个答案:

答案 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; }