追加计数重复在JavaScript字符串数组 [英] Appending the count to duplicates in a javascript string array

查看:93
本文介绍了追加计数重复在JavaScript字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想追加计数复制一个字符串数组条目。我有这样的,其中包含重复条目的数组。

I am trying to append the count to duplicate entries in a string array. I have an array like this which contains duplicate entries.

var myarray = ["John", "John", "John", "Doe", "Doe", "Smith", 
               "John", "Doe", "Joe"];

我所需的输出是

var newArray = ["John - 1", "John - 2", "John - 3", "Doe - 1", 
                "Doe - 2", "Smith", "John - 4", "Doe - 3", "Joe"];

什么是做到这一点的最好方法是什么?

What is the best way to do this?

推荐答案

var counts = {}, newArray = [];

// first pass, assign the counts
for (var i = 0; i < myArray.length; i++) {
   var name = myArray[i],
       count = counts.name;

   if (!count) {
      count = 1;
   } else {
      count++;
   }

   counts[name] = count;

   name = name + " - " + count;
   newArray.push(name);
}

// Undo changes made for names that only occur once
for (var i = 0; i < myArray.length; i++) {
   var name = myArray[i],
       count = counts.name;

   if (count === 1) {
      newArray[i] = name;
   }

}

请注意我用很简单的JavaScript来保持解决方案简单易读,易懂。请注意,你必须传递数组的两倍以上。对于非常大名单,这是不是很有效。

note I'm using very simple javascript to keep the solution easily readable, understandable. Note you have to pass over the array twice. For very large lists, this is not very efficient.

我没有测试这一点,但这样的事情应该工作。

I didn't test this, but something like that should work.

这篇关于追加计数重复在JavaScript字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆