transforming a for loop into an array filtering operation

Trying to enhance performance, this snippet of JavaScript code employs the array.filter instead of a traditional for loop. Surprisingly, the expected results are not achieved as intended. The purpose is to identify the names of students that match those in the searchWords array.
Any thoughts on why this is happening? Thank you.

let searchWords = ['john','matt','marry'];
let students = ['matt','jack'];
let names = [];
for (let i = 0; i < searchWords.length; i++) {
   if (students.indexOf(searchWords[i]) !== -1) {
       names.push(searchWords[i]);
   }
}
console.log(names.length); // => 1 "correct"

names = [];
names = searchWords.filter(x => students.filter(y => students.indexOf(x) !== -1));
console.log(names.length); // => 3 "incorrect"

Answer №1

By incorporating the filter line, an additional loop has been introduced to the process. The revised version should read:

names = searchWords.filter(x => students.indexOf(x) !== -1);

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

Multi-dimensional array: Include an extra array if the desired value is not located

I am currently working on a project that involves using Google tables to create a report based on data retrieved from my MYSQL Database. The issue I'm encountering is that there are 5 header values: ['Call Disposition', 'Answered' ...

Enhancing specific child value in Firebase Database using JavaScript: Exploring Firebase Realtime capabilities

I have a database structure where I need to update the value of isseen to true when the sender is equal to "5". Here's an example of my database structure: Chats -LvuhnORi1ugp8U2Ajdq isseen: "false" message: "hi" receiver: "OX0pReHXfXUTq1XnOnTSX7moiG ...

Secure your data with public key encryption and decryption using the Crypto Module in NodeJS

I have a challenge with encrypting/decrypting data using a public key that is stored in a file. The code snippet below illustrates my approach: encryptWithKey (toEncrypt, publicKeyPath) { var publicKey = fs.readFileSync(publicKeyPath, "utf8"); ...

Acquire data from an HTML Element

I was provided with the following div that was already created for me: <div data-sudo-slider='{"slideCount":1, "moveCount":1, "customLink":"#slider-nav a", "continuous":true, "updateBefore":false, "effect":"sliceRevealDown", "auto":true, "speed":1 ...

issue with webpack-dev-server not refreshing after changes to HTML or Sass files

Here is the layout of my project: \root \webpack.config.js \public \ index.html \ ... \ css \ directives \ views \ dist (webpack output) \app.js ...

"Enhance your website with Express.js and eliminate the need for full

As I continue to work on my website, I am faced with a challenge. While the page is not overly large, I want to ensure that when navigating to different tabs in the navbar, the entire site does not have to reload each time. Currently, I am using express.js ...

The value of the cookie is not set (version 2.0.6 of react-cookie)

I am encountering an issue with implementing react cookies version 2. I am using webpack-dev-server for testing. Below is the console log: Warning: Failed context type: The context cookies is marked as required in withCookies(App), but its value is unde ...

Using NgTable to sort and filter selections

I am working with two select elements. The first select is populated with names, and I would like the second select to only display the ages corresponding to the selected name. For example: If I select Jacob in the first select, I want the Age select to ...

CodeIgniter 4 Route Fails to Respond when a Different Value is Provided

I am currently engaged in self-studying Code Igniter 4. My focus is on inserting records irrespective of transactions. I have defined parameters such as Add, Edit and Delete. In the case of 'Add' being the passed value, a new record will be inser ...

Choosing an element from a 2-dimensional array in Ruby 1.9

Consider the following 2D array called sample: sample = [["Tom",1],["Jerry",2]] I want to retrieve the value "Jerry" from this array. Currently, I'm using: sample.select{|i| i if i[1] == 2}[0][0] I've also attempted: sample.select{|i| i if ...

Using javascript, hide or show a div without using jquery or the display:none property

I am looking for a way to show/hide a div up and down, but I have some requirements: I cannot use jQuery: toggle(), slideToggle(), fade, animate, etc. all use display: none, and I need the div to still occupy space in the DOM (I will be processing things ...

"Jest test.each is throwing errors due to improper data types

Currently, I am utilizing Jest#test.each to execute some unit tests. Below is the code snippet: const invalidTestCases = [ [null, TypeError], [undefined, TypeError], [false, TypeError], [true, TypeError], ]; describe('normalizeNames', ...

When incorporating Typescript into HTML, the text does not appear in bold as expected

Issue with bold functionality in Typescript Hey there, I am currently involved in an Angular project and I came across a problem with a function in a Typescript file that is supposed to bold a specific segment of text formatText() { ......... ...

Having issues with adding elements to an array object in JavaScript

I've got some HTML code that looks like this: HTML: <INPUT TYPE=CHECKBOX NAME="clcik" onClick="add('1234','blah')" /> <input type="hidden" id="project" value="" /> JS: function add(obj1 , obj2){ var jsonAr ...

Retrieve the value of a JSON array containing only a single object using jQuery

In my project, I have a jQuery file and a PHP file. If the PHP file successfully completes the process, it returns the value 2 using `echo json_encode(2)`. I am able to catch this value in the jQuery file and display a string on an HTML div without any iss ...

Capturing errors during function declaration in JavaScript

A problem has arisen in the below function definition due to a script error function foo () { try { var bar = function() { ERROR } } catch (exception) { console.debug("exception"); } } foo(); However, th ...

Choosing a JSON item based on its numerical position rather than by its name

I am attempting to store a JSON object containing information in multiple languages. I am uncertain if the way I have implemented it is optimal, so any suggestions are appreciated. My current issue is that I am unsure how to access the first language with ...

Missing folders in npm package

After successfully creating and publishing a private npm package, I noticed an inconsistency in the file structure when installing it on another project: Library.Util | |__index.js | |__package.json The original file structure of the package includes a t ...

Could the abundance of JavaScript files in Angular 2 be hindering its performance?

Having experience with Angular 1.x, I am now delving into the world of Angular 2. As I begin, I am struck by the multitude of js scripts required to be added to our index.html file just to get started. Even when excluding angular's own js files and c ...

Managing dependencies with Yarn or npm

While experimenting with remix and mui v5, I encountered some issues. When using npm and running npm run dev, I received the following error: Error: Directory import '.../playground/remix-mui-dev/node_modules/@mui/material/styles' is not supporte ...