Delete occurrences of an element if it occurs more than n times?

Someone plz explain whats happening inside the filter function with object cache?

//  deleteNth ([20,37,20,21],1) // return [20,37,21]
function deleteNth(arr,x) {
  var cache = {};
  return arr.filter(function(n) {
    cache[n] = (cache[n]||0) + 1;
    return cache[n] <= x;
  });
}
function deleteNth(arr,x) {
//Define a cache object;
  var cache = {};
  return arr.filter(function(n) {
  //The filter() method creates an array filled with all array elements that pass a test (provided as a function)//////
    cache[n] = (cache[n]||0) + 1;
  //The function returns every array element that is equal or smaller than x//////
    return cache[n] <= x;
  });
}

what test in this line?

cache[n] = (cache[n]||0) + 1;

The filter function takes each element of the array, and assigns its value to N.
It then increments a property of the cache object corresponding to that value.
If the cache property’s value (the count of occurances of value N) is less than or equal to x, the value is allowed to remain in the array, otherwise it is filtered out.

(cache[n]||0)+1 is meant to be a shorthand of:

if(typeof cache[n] === "undefined") {
    cache[n] = 0;
}
cache[n] += 1;

(Though its not strictly that, as it technically means “if (anything-that-evaluates-to-false) {”, but because the object was created empty inside the function, we can be sure that the properties of the object are either undefined or a non-zero number.)

The idea being you cant add 1 to an undefined property, so it substitutes a 0 if there would be an undefined there.

function should probably be named something else, as “deleteNth” sounds like it’s hunting specifically for the Nth, not more-than-Nth…

1 Like

That was how I read the action based on the naming. i.e. instead of

//  deleteNth ([20,37,20,21],1) // return [20,37,21]

because it was being passed “1”, it would delete the first array member. So going by the name I would expect the return to be “37,20,21”.

Not that my choice of names are always the best, but I would probably name it something like “removeDuplicates” or “uniqueValues” instead.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.