Renaming duplicates in Javascript Array

瘦欲@ 提交于 2019-12-12 18:33:24

问题


I'm looking for the most efficient way to rename (append-1, -2 etc.) a variable, if it already exists in a string.

So I'm keeping an array"

dupeCheck = [];

And as soon as I see that a variable:

var UID;

Is already in my dupeCheck array, I want to immediately append the value of UID with -1,

Also, I need to prevent a third duplicate becoming string-1-1, but rather string-2..

I saw this: Appending the count to duplicates in a javascript string array before, but It's nog exactly what I want...

Any smart ideas? I prefer jQuery..

/Edit:

For example:

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;
     }

So when we get out of the "UID" case, I want to make sure it has a unique value


回答1:


The best way to keep a list of things you're checking for dups on is to have them in an object, not an array so you can look them up quickly and then generate a unique suffix that isn't already in use each time. This function allows you to pass an id into the function and have the function return a unique version of that id that isn't already in use. If what was passed in was not in use, it just returns that. If what was passed in was in use, it strips any suffix off and generates a new suffix that isn't already in use and returns the newly minted id. The newly minted id is then stored in the data structure so it won't be duplicated in the future too.

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);
}



回答2:


You can wrap the functionality in a function to be able to reuse it. The function below takes a list of strings and returns the -1, -2 etc. suffixed list of strings.

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;
}

For example, an input of

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

returns an output of

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

To see it in action, here is a link to a jsFiddle example.




回答3:


It's a little difficult to understand your question, but please let me know if this is what you were referring to. Suppose we have a string of words, and some of the words repeat. We want to modify those repeated words with a new suffix, such as -1 or -2, depending which instance it is.

// 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(" ") );

Our result is

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


来源:https://stackoverflow.com/questions/10643933/renaming-duplicates-in-javascript-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!