What could be causing the error I'm encountering while attempting to utilize Array.includes as the function for Array.filter in my JavaScript code?

During a recent javascript project, I attempted something like the following code snippet. To my surprise, it did not work and instead produced an error message.

const test = [1, 2, 3, 4];

const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(test.includes);

console.log(something);

TypeError: Cannot convert undefined or null to object
    at includes (<anonymous>)
    at Array.filter (<anonymous>)
    at evalmachine.<anonymous>:3:45
    at Script.runInContext (vm.js:74:29)
    at Object.runInContext (vm.js:182:6)
    at evaluate (/run_dir/repl.js:133:14)
    at ReadStream.<anonymous> (/run_dir/repl.js:116:5)
    at ReadStream.emit (events.js:180:13)
    at addChunk (_stream_readable.js:274:12)
    at readableAddChunk (_stream_readable.js:261:11)

I wonder if this is a bug in javascript or if I am simply misunderstanding something. The two working alternatives are shown below:

const test = [1, 2, 3, 4];

const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(item => test.includes(item));

console.log(something);

And:

const test = [1, 2, 3, 4];

const someFunc = theThing => test.includes(theThing);
const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(someFunc);

console.log(something);

As I strive for a more functional programming style and aim for point-free patterns where possible, encountering such inconsistencies is slightly frustrating.

Edit: This is not repeated content. My question is not about This, but rather how it interacts with the includes function specifically.

Answer №1

If you want to utilize the thisArg of Array#filter along with the object function prototype, there is a way to do so.

const test = [1, 2, 3, 4];

const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(Array.prototype.includes, test);

console.log(something);

However, keep in mind that Array#includes introduces a second parameter fromIndex, which can be passed through the filter function and might not be intended.

In such scenarios, it might be more suitable to opt for a direct approach.

const test = [1, 2, 3, 4];

const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(v => test.includes(v));

console.log(something);

Answer №2

test.includes refers to a function, but when used without context, it loses its reference to this.

 const fn = test.includes;
 fn(1); // will not work
 fn.call(test, 1); // works because `this` is explicitly set.

To resolve this issue, you can pass the second parameter in filter,

 .filter(test.includes, test)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

issue with retrieving data from PHP script via ajax

My attempts to use AJAX to call a PHP script have been unsuccessful. I added an echo alert statement in my deleteitem.php script to ensure it was being called, but no matter what I tried, it never executed. Both the PHP script and the JS script calling it ...

req.next does not exist as a function [END]

I am currently working on developing a website and I have encountered an issue in the dashboard stage. The error message TypeError: req.next is not a function keeps appearing, particularly when trying to create a subpage for the dashboard. I am utilizing t ...

Storing data with ElectronJS

I am currently working on an Electron JS and React JS offline application. One of the initial steps in my launch process involves loading a large file that is over 1 GB in size and cannot be divided. This causes a delay of approximately 50-60 seconds whi ...

A guide on switching the status of various inputs in a table based on the selection of a radio button

In the scenario below, let's consider the following HTML structure: <tr> <td> <label for="c1_testRdio">Have you taken any tests in this class?:</label> <br> <label>Yes<input type="rad ...

What is the reason for TypeScript allowing this promise chain without any compilation errors?

Although I am still relatively new to Typescript, I find myself grappling with a particular issue that has been perplexing me. I am unsure why the following code snippet triggers a compilation error: // An example without Promises (does not compile) funct ...

Maximizing the efficiency of table search with AngularJS filter

Currently, I am implementing pagination in my tables using a library called Angular Table. This library utilizes the ng-repeat directive to create its own array from the data I provide. Due to this implementation, I am unable to utilize the search filter ...

Transforming the exterior designs in Angular

I am in the process of transitioning a product management admin site to Angular. Currently, all my views (such as the product list, detail view, and edit) are displayed inside an ng-view on my admin page, which is working well. However, I have a link for e ...

Node.js population process

Hello, I am currently exploring Node.js and facing an issue with the populate() method. My goal is to populate the user model with forms. Here is the structure of the model: const UserSchema = new Schema({ firstName: { type: 'string&a ...

When loading a page with Puppeteer using the setContent method, images may not be loaded

Currently, I am experiencing an issue with Puppeteer where it does not load resources that are specified with relative paths (such as background.png in the image src or in CSS url()). When I try to load the content of a local file using setContent(), the o ...

Enhance Your Website with Dynamic Autocomplete Feature Using jQuery and Multiple Input Search Functionality

I am working on a form with three input fields. Here is the HTML structure: Name<input type="text" class="customer_name" name="order[contact][first_name]"/><br/> Email<input type="text" class="customer_email" name="order[contact][email]"/& ...

Tips for incorporating a pause or delay into if-else statements

Trying to optimize my semi-automated JavaScript code so it runs at a slower pace. Currently, it fetches detailed data from 100 listings one by one at a speed of around 15 times per second. While this works well in some aspects, it makes tracking which elem ...

Transferring data in PDF format through email with the help of PHPMailer and html2pdf

Having trouble sending PDF or PNG files over email despite multiple attempts. Despite reading countless articles on the topic, nothing seems to be working as suggested. Can anyone provide assistance? I am using PHPMailer along with html2pdf and html2canva ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...

Adding elements to an array appears to cause the previously created object to react

I am encountering a situation where once I add an object to an array, it becomes reactive to any changes made. // actions.js export const addToCart = ({ commit }) => { commit('addToCart'); // successfully updates the state setTimeout ...

Ways to determine the total amount of existing files in a directory

For the purpose of file management and moving files to another folder, I am attempting to determine the count of files that already exist in a specified folder. foreach($checkboxfiles as $checkboxfile) { $src_file = $checkboxfile; $fileName = bas ...

The ajaxStart() and ajaxStop() methods are not being triggered

I'm currently working on a Q/A platform where users can click on specific questions to be redirected to a page dedicated for answers. However, when a user tries to answer a question by clicking the "Answer" link, certain background processes such as ...

Tips for building a carousel-style transition using React Router

I am looking to implement a carousel animation in my React Router. My website has pages named A, B, C, and D. When transitioning from page A to B, I want the animation to move from right to left. When going from B to A, I want it to move from left to rig ...

Ascending Order of WordPress Locations

I need help sorting the order of locations in Word Press, where the locations are stored within the posts meta data. On my home page, there is a drop-down box for users to select a location, and I would like them to be ordered from A - Z <?php ...

Adding data from two different arrays to a MySQL table using PHP

I am attempting to populate a table with values from two arrays. The goal is to insert the corresponding values from array1 and array2 into the table as rows. For example, the table row should look like this: value1, array1[0], array2[0] ... value1, array ...

Setting up a specific print media query for the body element through JavaScript

I'm facing an issue with my web page that has a bootstrap modal which pops up when a button is clicked. I've added a print media query to print the content of the modal, but it's causing a problem. When I include the media query in the CSS, ...