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

时间:2019-02-05 19:19:52

标签: javascript

晚上好,我尝试检测字符串中的重复字符。更具体地说,我试图在一个数组中查找多达两个不同的重复项。如果存在一个重复项,请添加一个子字符串,如果存在另一个重复项,请添加一个不同的子字符串。有什么办法吗?

这是我到目前为止的一些示例代码:

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”

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

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

uniqueArray ( CodeFieldArray  )

答案 1 :(得分: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 array推入unique时,我们都将numOfDup减少(以处理只有一个重复项或没有重复)。
  • 最后加入,