繁体   English   中英

JavaScript - 改进 object 的动态数组。 保持重复

[英]JavaScript - Improvement of the dynamic array of object. Maintenance of repetitions

我有这个脚本:

console.log(solution([2, 1, 3, 5, 3, 2]))

function solution(inputArray) {
  let arrMap = []
  
  for (let i = 0; i < inputArray.length; i++) {   
    var e = arrMap.find(s => s.element == inputArray[i])

    if (e) {
      e.repeated = true;
      e.firstPosition = e.position
      e.lastPosition = i
      e.quantity++
      delete e['position'];
    
    } else {
      arrMap.push({
        repeated: false,
        element: inputArray[i],
        position: i,
        quantity: 1
      })
    }
  }  
  
 return arrMap    
}

该脚本返回一个动态构造的 object:

[
  {
    repeated: true,
    element: 2,
    quantity: 2,
    firstPosition: 0,
    lastPosition: 5
  },
  { repeated: false, element: 1, position: 1, quantity: 1 },
  {
    repeated: true,
    element: 3,
    quantity: 2,
    firstPosition: 2,
    lastPosition: 4
  },
  { repeated: false, element: 5, position: 3, quantity: 1 }
]

我想只保留几个重复的元素。 如果我们有那个条目:

/*           pairs:    V     V     V  V        */   
 console.log(solution([2, 1, 3, 5, 3, 2, 2]))
/*                                       ^
                                         | DO NOT INCLUDE THIS ITEM IN THE 
                                         | OUTPUT ARRAY! ITEM LEFT!
/*

我不想包括最后一项,在这种情况下是2 因为在这种情况下,我们将在这对中留下一个。 我只想接受最多只有几个元素。

在下面的另一个示例中,我也不想包含超过允许的这对。 我必须记住,我只会接受一对。 我该怎么办?

/*            pairs:  V     V     V  V            */
console.log(solution([2, 1, 3, 5, 3, 2, 2, 2]))
/*                                      ^  ^
                                        |  |

                                      DO NOT INCLUDE THESE 2 ITEMS IN THE 
                                      OUTPUT ARRAY! PAIR LEFT!
                                      --------------------------------- 
                                      I Already have a pair 
                                      with this item!
*/

我认为您需要使用allowOnlyDuplicates function 来限制数组中的两个值或先过滤它,然后再使用您的solution function。

function allowOnlyDuplicates(yourArr) {
    var countValue = [];

var onlyDuplicates = [];
for (var i = 0; i < yourArr.length; i++) {
  var num = yourArr[i];
  countValue[num] = countValue[num] ? countValue[num] + 1 : 1;

  if (countValue[num] <= 2 ) {
    onlyDuplicates.push(num);
  }
}
return onlyDuplicates;
}

然后

console.log(solution(allowOnlyDuplicates([2, 1, 3, 5, 3, 2, 2, 2])))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM