首页 > 解决方案 > 如何检测数组中的重复字符,并相应地创建一个参数?

问题描述

晚上好,我试图检测字符串中的重复字符。更具体地说,我试图在一个数组中找到最多两个不同的重复项。如果有一个重复,则添加一个子字符串,如果有另一个重复,则添加一个不同的子字符串。有没有办法做到这一点?

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

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

解决方案


你可以这样做:

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

uniqueArray ( CodeFieldArray  )

推荐阅读