2

如果变量已经存在于字符串中,我正在寻找最有效的方法来重命名(append-1、-2 等)变量。

所以我保留了一个数组”

dupeCheck = [];

一旦我看到一个变量:

var UID;

已经在我的 dupeCheck 数组中,我想立即将 UID 的值附加为 -1,

另外,我需要防止第三个重复成为 string-1-1,而是 string-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;
     }

所以当我们摆脱“UID”的情况时,我想确保它具有唯一的价值

4

3 回答 3

7

您可以将功能包装在一个函数中以便能够重用它。下面的函数接受一个字符串列表并返回以-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;
}

例如,输入

[ "Barry", "Henk", "Jaap", "Peter", "Jaap", "Jaap", "Peter", "Henk", "Adam" ]

返回的输出

[ "Barry", "Henk-1", "Jaap-1", "Peter-1", "Jaap-2", "Jaap-3", "Peter-2", "Henk-2", "Adam" ]

要查看它的实际效果,这里是 jsFiddle 示例的链接。

于 2012-05-17T22:04:30.883 回答
2

理解您的问题有点困难,但请让我知道这是否是您所指的。假设我们有一串单词,其中一些单词重复。我们想用一个新的后缀来修改那些重复的单词,比如-1or -2,这取决于它是哪个实例。

// Start by creating our string, word array, and result array
var string = "one two one one two one three three one three",
    values = string.split(" "), result = [];

// For every word in the values array
for ( var i = 0; i < values.length; i++ ) {

  // Set a word variable, and an integer suffix
  var word = values[i], int = 1;

  // While our current word (with/without suffix) exists in results
  while ( strArr(word, result) >= 0 ) 
    // Increment the suffix on our word
    word = values[i] + "-" + int++;

  // Push word into result array
  result.push(word);
}

// Function for determining if a string is in an array
function strArr(s,a){
  for ( var j = 0; j < a.length; j++ )
    if ( a[ j ] == s ) return j;
  return -1;
}

// Compare the before and after
console.log( string );
console.log( result.join(" ") );

我们的结果是

one two one one two one three three one three
one two one-1 one-2 two-1 one-3 three three-1 one-4 three-2
于 2012-05-17T21:59:02.227 回答
1

保存您正在检查的重复项的列表的最佳方法是将它们放在一个对象中,而不是一个数组中,这样您就可以快速查找它们,然后生成一个每次都没有使用的唯一后缀。此函数允许您将 id 传递给函数并让函数返回该 id 的唯一版本,该版本尚未使用。如果传入的内容没有被使用,它只会返回它。如果传入的内容正在使用中,它会删除任何后缀并生成一个尚未使用的新后缀并返回新生成的 id。然后将新生成的 id 存储在数据结构中,因此将来也不会重复。

var idList = {};

makeIdUnique(id) {
    if (id in idList) {
        // remove any existing suffix
        var base = id.replace(/-\d+$/, "");
        // generate a new suffix
        var cnt = idList[base] || 1;
        // while new suffix is in the list, keep making a different suffix
        do {
            id = base + "-" + cnt++;
        } while (id in idList);
        // save cnt for more efficient generation next time
        idList[base] = cnt;
    }
    // put the final id in the list so it won't get used again in the future
    idList[id] = true;
    // return the newly generated unique id
    return(id);
}
于 2012-05-17T21:58:10.417 回答