2015-06-10 40 views
0

我读过一些帖子,其中重复项从数组中删除。例如,具有“one”,“one”,“two”,“three”的数组将使用我在某些帖子中找到的代码返回“one”,“two”,“three”。我需要删除两个值,所以“一个”,“一个”,“两个”,“三个”将返回“两个”,“三个”。我正在解析文件并根据正则表达式搜索项目。这是我的代码。虽然有时候我正在解析的文件中有重复的数据。我需要删除这些数据。删除对象数组中的重复项

function parseText(text) 
    { 
     var records = text.match(fileRegex); 
     var fileArray = []; 


     if (records != null) { 
      records.forEach(function (element, index, array) { 
       var matches = elementRegex.exec(element); 

       if (matches != null) { 
        var year = matches[parseSettings.ParseYearPosition]; 
        if (year == 2) 
        { 
         year = "20" + year; 
        } 
        var journalDate = new Date(year, 
         matches[parseSettings.ParseMonthPosition] - 1, 
         matches[parseSettings.ParseDayPosition], 
         matches[parseSettings.ParseHourPosition], 
         matches[parseSettings.ParseSecondPosition], 0, 0); 

        var file = { 
         Id: null, 
         ImportDate: moment(importDate).format(), 
         JournalDate: moment(journalDate).format(), 
         TraceNumber: parseInt(matches[parseSettings.ParseTraceNumberPosition]), 
         Amount: parseFloat(matches[parseSettings.ParseAmountPosition]), 
         Deleted: false, 
         Dirty: true 
        }; 
        fileArray.push(file); 

       } 
      }); 

      deferred.resolve(fileArray); 
     } 
+0

的(HTTP [从对象在JavaScript数组删除重复]可能重复。 com/questions/2218999/remove-duplicates-from-an-a-array-of-objects-in-javascript) –

回答

0

可以使用一个简单的for循环,检查是否fileArray [I] == fileArray第[i + 1],如果是从阵列拼接它们。

更新

所以for循环之前您解决fileArray会是什么样子://计算器:

for(var i = 1; i <= fileArray.length;) { 
    if(fileArray[i] == fileArray[i-1]) { 
     fileArray.splice(i-1, 2); 
     i+=2; 
    } 
    else 
     i++; 
} 
+0

我不确定这会起作用。它是一组对象。拼接将删除我需要的一个项目。所以fileArray [0]将会是'{Id:null,ImportDate:ImportDate =“2015-06-10T11:32:24-05:00”,TraceNumber:1111,Amount:1.11,Deleted:false,Dirty:true}'并且fileArray [1]也可能是'{Id:null,ImportDate:ImportDate =“2015-06-10T11:32:24-05:00”,TraceNumber:1111,Amount:1.11,Deleted:false,Dirty:true} '所以我需要踢双fileArray [0]和fileArray [1] – rsford31

+0

你可以告诉splice你想从索引i开始删除多少项目,所以如果fileArray [i] == fileArray [i + 1]你可以做fileArray.splice(i,2) – Guinn

+0

@ rsford31检查我更新的答案,它应该做你想做的! – Guinn