如何检测数组中的重复的字符,并创建相应的参数?

问题描述 投票:2回答:2

晚上好,我试图在字符串中检测到重复的字符。更具体地讲,我想找到了一个阵列内两个不同的副本。如果有一个重复的,添加子字符串,如果有另一种重复,添加不同的子串。有没有办法做到这一点?

下面是一些示例代码,我到目前为止有:

var CodeFieldArray = ["Z80.0", "Z80.1", "Z80.0", "Z70.4"]; 

/* We have an array here used to create the final string at the end of the 
code.  It is a dummy array with similar variables in my actual code.  For 
reference sake, there may be only one object in the array, or 7 total, 
depending on the user's input, which is where the duplicate detection should 
come in, in case the user enters in multiples of the same code. */

var i, Index;

for (i = 0, L = 0; i < CodeFieldArray.length; i++) {  
  Index = CodeFieldArray[i].indexOf(CodeFieldArray[i]);
  if(Index > -1) L += 1;
  Extra0 = CodeFieldArray.indexOf("Z80.8");
  Extra1 = CodeFieldArray.indexOf("Z80.9");
  if(L >= 2 && Extra0 == -1) CodeFieldArray.push("Z80.8");
  Extra0 = CodeFieldArray.indexOf("Z80.8");
  if(L >= 4 && Extra0 != -1 && Extra1 == -1) CodeFieldArray.push("Z80.9");
  console.println(Extra0);
}

/*^ we attempted to create arguments where if there are duplicates 
'detected', it will push, "Z80.8" or, "Z80.9" to the end of the Array.  They 
get added, but only when there are enough objects in the Array... it is not 
actually detecting for duplicates within the Array itself^*/

function UniqueCode(value, index, self) { 
    return self.indexOf(value) === index;
}
CodeFieldArray = CodeFieldArray.filter(UniqueCode);
FamilyCodes.value = CodeFieldArray.join(", ");

/* this is where we turn the Array into a string, separated by commas.  The expected output would be "Z80.0, Z80.1, Z70.4, Z80.8"*/

我也有在那里将增加“Z80.8”或“z80.9”如果它们不存在,但它们正在增加,只要有在阵列足够的对象。我的for循环,没有特别的检测重复自己。如果有专门检测重复,并创建一个基于关的一场争论的方式,那么我们会做盛大。预期结果将是 “Z80.0,Z80.1,Z70.4,Z80.8”

javascript
2个回答
0
投票

您可以使用SetforEachincludes

var CodeFieldArray = ["Z80.0", "Z80.1", "Z80.0", "Z70.4"];
let unique = [...new Set(CodeFieldArray)];
let match = ['Z80.8','Z80.9'];
let numOfDup = CodeFieldArray.length - unique.length;

if(numOfDup){
  match.forEach(e=>{
    if(!unique.includes(e) && numOfDup){
      unique.push(e);
      numOfDup--;
    }
  })
}

console.log(unique.join(','))

这样的想法是

  • 使用Set获得唯一值。
  • 现在看到original arraySet的长度差来获得副本的数量。
  • 现在将遍历match array每次我们推项目从match arrayunique我们通过这样减少numOfDup时间(来处理,我们只有一个重复或没有重复的情况下)。
  • 最终参加由,

0
投票

你可以这样做:

var uniqueArray = function(arrArg) {
  return arrArg.filter(function(elem, pos,arr) {
    return arr.indexOf(elem) == pos;
  });
};

uniqueArray ( CodeFieldArray  )
© www.soinside.com 2019 - 2024. All rights reserved.