我正在尝试使用lodash
将计数附加到重复项。
例如,
let arr = ["apple", "apple", "apple", "banana", "mango", "mango"];
然后我希望我的输出
let modifiedArr = ["apple1", "apple2", "apple3", "banana",
"mango1", "mango2"];
答案 0 :(得分:3)
您可以尝试这样的事情:
value + count
let arr = ["apple", "apple", "apple", "banana", "mango", "mango"];
let hashMap = {};
const result = arr.reduce((p, c) => {
hashMap[c] = (hashMap[c] || 0) + 1;
p.push(`${c}${hashMap[c]}`);
return p;
}, []);
console.log(result);
答案 1 :(得分:2)
您可以将Array.map()与ES6 Map结合使用:
const arr = ["apple", "apple", "apple", "banana", "mango", "mango"];
const result = arr.map(function(item) {
const count = (this.get(item) || 0) + 1; // get the current count
this.set(item, count); // update the map with the current count
return item + count;
}, new Map()); // the map is the this of the callback
console.log(result);