-5

I came across this piece of code which checks if number of occurrences of an element in an array is greater than it is specified, and if yes it will remove the number:

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

But I didn't understand the code from here: arr.filter(function(n){cache[n] = (cache[n]||0) + 1;return cache[n] <= x;}); Can anyone please explain in simple words what happens here and how does cache[n] part work.

Why is cache[n] incremented?

Thanks!

Jithin
  • 169
  • 9
  • 5
    Have you read the [documentation](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) or read [Logical operators in JavaScript — how do you use them?](/q/4535647/4642212)? See [What does this symbol mean in JavaScript?](/q/9549780/4642212) and the documentation on MDN about [expressions and operators](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) and [statements](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements). – Sebastian Simon Jun 22 '21 at 05:55
  • I know what the `||` operator does. But I didn't understand why is it incremented... – Jithin Jun 22 '21 at 06:05

1 Answers1

1

The arr.filter() begins by iterating over each item in the array and this case each item is represented by 'n'.

This item is then added to the empty object where 'n' is the key and the value is then incremented by one for each new item added to the object.

The return statement uses the cache to do a check of what 'n' values are less than or equal to x. If it returns false they are not added into the new array that is created. So if 'x' is 3 it will remove everything after the first three items from the array.

EDIT

Another way of writing the function which might make it more clear could be

function deleteNth(arr,x) {
    return arr.filter((item, index) => {
        if (index <= x) {
          return item;
        }
    });
}
Mitchell Stone
  • 260
  • 2
  • 10