数组中的项目不会增加

时间:2019-06-14 16:44:45

标签: javascript arrays

如果数组中有重复项,我想增加该值。这些是我的控制台日志结果:

this is the map { '1': 1, '2': 1, '3': 1, '4': 2 }
this is the values more than one 4
this is iitem before 4
this is item after 5
this is iitem before 4
this is item after 5
this is the array here [ 1, 4, 2, 3, 4 ]
[ 1, 4, 2, 3, 4 ]

和代码:

const incrementDuplicate = function(value, arr){
      for(let item of arr){
        if(item.toString() === value.toString()){
          console.log('this is iitem before', item);
          item = item+1;
          console.log('this is item after', item)
        }
      }
      return arr;
    }
    
    
    const uniqueArraySum = function(arr){
      let map = {};
      let newArray = [];
      for(let item of arr){
        if(!map[item]){
          map[item] = 1;
        } else{
          map[item]++;
        }
      }
      console.log('this is the map', map);
    
      for(let item in map){
        if(map[item] !== 1){
          console.log('this is the values more than one', item);
          newArray = incrementDuplicate(item, arr);
          console.log('this is the array here', arr);
        }
      }
      return newArray;
    }


    console.log(uniqueArraySum([1,4,2,3,4]));

2 个答案:

答案 0 :(得分:1)

我认为您走在正确的道路上,基本上,创建counts字典/地图的想法是可行的。您只需要在遍历原始数组时引用它,即可查看该元素是否出现多次,因此需要递增:

const incrementDuplicates = arr => {
  let countDict = getCountDict(arr)
  for (let i = 0; i < arr.length; i++) {
    if (countDict[arr[i]] > 1) {
      arr[i]++
    }
  }
  return arr
}

const getCountDict = arr => {
  let countDict = {}
  arr.forEach(val => countDict[val] = (countDict[val] || 0) + 1)
  return countDict
}

console.log(incrementDuplicates([1,4,2,3,4])) 

答案 1 :(得分:0)

我认为问题在于您试图通过迭代器变量对数组进行变异。如果是原始值,则无法使用,因为JS不支持指针。

所以您应该这样:

for(let i=0; i<arr.length; i++){
    if(arr[i].toString() === value.toString()){
      console.log('this is item before', arr[i]);
      arr[i] = arr[i]+1;
      //or even simpler `arr[i]++`
      console.log('this is item after', arr[i])
    }
}
相关问题