Codewars-如果元素出现n次以上,则删除该元素的出现

时间:2019-06-07 21:23:45

标签: javascript

我刚刚在Codewars上完成了this challenge

我已经用自己的方法完成了该问题,但是有人可以向我解释最佳实践答案。能以某种方式解释此代码的功能吗?

function deleteNth(arr,x) {
  var cache = {};
  return arr.filter(function(n) {
    cache[n] = (cache[n]||0) + 1;
    return cache[n] <= x;
  });
}

我这样做了:

function deleteNth(arr,n){
  var count = 0;
  //loop backwards so it removes duplicates from the right
  for(let i= arr.length; i > 0; i--){
    for(let j=0; j < arr.length; j++){
      if (arr[i] == arr[j]){
        count += 1
      }
    }
    if(count > n){
      arr.splice(i,1);
      i = arr.length;
    }
        count = 0;
  }
  return arr;  
}

1 个答案:

答案 0 :(得分:1)

这是第一个代码的工作方式。如果您了解过滤器功能,这是一个非常不错的解决方案,并且非常容易阅读。

function deleteNth(arr, x) {
  // Create an empty object to store how many times each object exists
  var cache = {};
  // Call the filter function, the delegate is called once for each item
  // in the array and you return true or false depending on if it should
  // be kept or not
  return arr.filter(function(n) {
    // Use the item as key and store the number of times the item has appeared.
    // (cache[n]||0) fetches the current value of cache[n] or zero if it doesn't
    // exist. Then add one to it and store it.
    cache[n] =(cache[n]||0) + 1;
    // If the number of times it has appeared in the array is less or equal to
    // the limit then return true so the filter function keeps it.
    return cache[n] <= x;
  });
}