Javascript附加计数重复

时间:2017-12-11 05:46:37

标签: javascript duplicates lodash

我正在尝试使用lodash将计数附加到重复项。 例如,

let arr = ["apple", "apple", "apple", "banana", "mango", "mango"];

然后我希望我的输出

let modifiedArr = ["apple1", "apple2", "apple3", "banana", 
            "mango1", "mango2"];

2 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情:

逻辑:

  • 创建一个包含重复计数的hashMap
  • 将值推送到数组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);