Try*_*ace 2 arrays jquery duplicates
我正在寻找一种最有效的方法来重命名(append-1,-2等)一个变量,如果它已经存在于一个字符串中.
所以我保持一个阵列"
dupeCheck = [];
Run Code Online (Sandbox Code Playgroud)
只要我看到一个变量:
var UID;
Run Code Online (Sandbox Code Playgroud)
已经在我的dupeCheck数组中,我想立即用-1附加UID的值,
另外,我需要防止第三个重复成为字符串-1-1,而是字符串-2 ..
我看到了这一点:将计数附加到javascript字符串数组中的重复 之前,但它正是我想要的......
任何聪明的想法?我更喜欢jQuery ..
/编辑:
例如:
var dupeUIDCheck = [];
$.each(data[IDS].UIDs[keys], function(keys, val)
{
var currString = val;
switch (key)
{
case "UID":
UID = unquote(currString);
//TODO:
//Detect if multiple UIDs are loaded from a single source, and
//rename them:
dupeUIDCheck.push(UID); //Push current ID onto existing array
//Check if ID exists
?
//If exists rename value of currString, save it in currString
newName = currSting;
break;
case "otherstuff":
//Other vars to parse
break;
}
Run Code Online (Sandbox Code Playgroud)
因此,当我们摆脱"UID"的情况时,我想确保它具有唯一的价值
您可以将功能包装在函数中以便能够重用它.下面的函数将字符串列表,并返回-1,-2等后缀的字符串列表.
function suffixDuplicates( list )
{
// Containers
var count = { };
var firstOccurences = { };
// Loop through the list
var item, itemCount;
for( var i = 0, c = list.length; i < c; i ++ )
{
item = list[ i ];
itemCount = count[ item ];
itemCount = count[ item ] = ( itemCount == null ? 1 : itemCount + 1 );
if( itemCount == 2 )
list[ firstOccurences[ item ] ] = list[ firstOccurences[ item ] ] + "-1";
if( count[ item ] > 1 )
list[ i ] = list[ i ] + "-" + count[ item ]
else
firstOccurences[ item ] = i;
}
// Return
return list;
}
Run Code Online (Sandbox Code Playgroud)
例如,输入
[ "Barry", "Henk", "Jaap", "Peter", "Jaap", "Jaap", "Peter", "Henk", "Adam" ]
Run Code Online (Sandbox Code Playgroud)
返回的输出
[ "Barry", "Henk-1", "Jaap-1", "Peter-1", "Jaap-2", "Jaap-3", "Peter-2", "Henk-2", "Adam" ]
Run Code Online (Sandbox Code Playgroud)
要查看它的实际效果,这里有一个指向jsFiddle示例的链接.