Skip to content Skip to sidebar Skip to footer

Javascript: Add Method To Array.prototype Object To Exclude Index Values From An Input Array

I want to write code that adds the doNotInclude method to the Array.prototype object. The purpose of my code is: does not include the index values from the array passed to doNotIn

Solution 1:

Basically it's checking to see if your input is an array, and if not, it makes it into a single element array.

This is because the logic of the code requires the input to be an array since it uses Array.includes(). This line will never execute if your input is always an array, so it's not technically necessary, but it would allow you to pass

1

as well as

[1]

and not get an error.

Solution 2:

The code if (!Array.isArray(arr)) arr = [arr]; is just a safeguard. It converts the argument arr into an array, if it's not already one. In other words, that piece of code enables the following behavior:

['zero', 'one', 'two'].doNotInclude(0) // Notice that the number is passed

Whereas without that safeguard, the above code would simply fail. Example:

// 1. With safeguardArray.prototype.doNotInclude = function (arr) {
  if (!Array.isArray(arr)) arr = [arr];
  returnthis.filter((val, i) => {
    if (!arr.includes(i)) return val;
  });
};

console.log(['zero', 'one', 'two'].doNotInclude(0)); // executes normally// 2. Without safeguardArray.prototype.doNotInclude = function (arr) {
  //if (!Array.isArray(arr)) arr = [arr];returnthis.filter((val, i) => {
    if (!arr.includes(i)) return val;
  });
};

console.log(['zero', 'one', 'two'].doNotInclude(0)); // fails

Post a Comment for "Javascript: Add Method To Array.prototype Object To Exclude Index Values From An Input Array"