我试图将计数附加到字符串数组中的重复条目.我有一个像这样的数组,包含重复的条目.
var myarray = ["John", "John", "John", "Doe", "Doe", "Smith",
"John", "Doe", "Joe"];
Run Code Online (Sandbox Code Playgroud)
我想要的输出是
var newArray = ["John - 1", "John - 2", "John - 3", "Doe - 1",
"Doe - 2", "Smith", "John - 4", "Doe - 3", "Joe"];
Run Code Online (Sandbox Code Playgroud)
做这个的最好方式是什么?
这是有效的,使用两遍Array.map():
var map = {};
var count = myarray.map(function(val) {
return map[val] = (typeof map[val] === "undefined") ? 1 : map[val] + 1;
});
var newArray = myarray.map(function(val, index) {
if (map[val] === 1) {
return val;
} else {
return val + ' - ' + count[index];
}
});
Run Code Online (Sandbox Code Playgroud)
第一遍记录每个唯一项目的查看次数,并返回与输入数组对应的数组,记录每个项目的当前计数.
第二遍将计数附加到总计数不是1的任何项目.
http://jsfiddle.net/alnitak/Z4dgr/的工作演示