Utilize a filter to verify if an element meets a specified condition, and if it does, retrieve the following

[ 'foo', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="05636a6a45633r6a2b66689w98">[email protected]</a>', 'bar.', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3a1a3gb292inflkf31v685n">[email protected]</a>' ]

An array is provided. I am required to identify words that start or end with a . and return the email address (which follows the word) if it meets the given criteria. In this instance, the word in question is 'bar.'. To do this, I need to utilize the filter function to retrieve '[email protected]'. The word and email are always sequential, even in arrays with multiple elements from which results need to be extracted.

return logins.filter((el, i) => el.match(/^\..+|.+\.$/) && i % 2 === 0);

I have successfully isolated 'bar.', but am uncertain of how to verify it and subsequently return the subsequent element. Is there a way to incorporate a ternary operation within the filter function to obtain the desired result?

Answer №1

Remember to use i-1 as a way to check the element that comes before the current one in cases where the index is odd.

let logins = [ 'foo', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb8d8484ab8d8484c5888486">[email protected]</a>', 'bar.', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea888b98aa888b98c4898587">[email protected]</a>' ];
console.log(logins.filter((el, i, arr) => i % 2 == 1 && arr[i-1].match(/^\.|\.$/)));

Answer №2

If you're looking for a specific element in an array, you can utilize the find method like this:

['apple', 'banana', 'cherry', 'date']
  .find(
    (item, index, arr) => item === 'cherry'
  )

The find() function will return the first element in the array that meets the criteria specified in the testing function.

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

What is the best way to access the attributes of a particular object following a triggered event?

I'm a bit unsure if my title makes sense, so allow me to explain. In a nutshell, I have 2 li elements within a ul list. What I aim for is that when one of these li elements is clicked, the text within that particular li is retrieved, and then an obje ...

Managing state with Apollo within a component

Greetings and thank you for taking the time to help me out. I am currently diving into the world of Apollo and React, but it seems like I am struggling with some logic here. On my main page index.js, I have initialized Apollo in the following way: export c ...

Struggling to create a foreach loop for a basic array in Perl and feeling unsure about the correct syntax

As a beginner in programming, I am currently learning my first language. In my class, we are using an older book from 2002 for reference. While this may not have much impact on your ability to help me, I thought it was worth mentioning. The Issue I am st ...

Code fails to function with images

Why is it not functioning properly? I would like to be able to click on next.jpg and have 2.png disappear while 1.png appears. <html> <head> <script type="text/javascript"> function next(id) { var currentImg = document.getElemen ...

Grab the div, position it accurately, and initiate an ajax call

So many tasks on my plate, but let's prioritize. Within a <div class="showcase">, I have numerous <div class="game"> elements, each with an onclick="addpop('delpopup.php?id=something&pos=somethingelse&box=image')" Does ...

Issue: `TypeError: store middleware is not a valid function`

In my React-Redux code, I have successfully combined the store and reducer in previous apps, possibly due to different versions of React and React-Redux. However, when setting up a new React project with the latest versions, I encountered an error: T ...

What is the process for generating a MongoDB collection in Node using a dynamic alias?

When inserting a node into a Mongo Collection, the command is: db.collection.insertOne({.........}); Currently, my collection contains a string inputted by the user: db.$$<VarCollectionName>.insertOne({........]); However, attempting this causes ...

How can I use querySelector in JavaScript to target all div elements that have the same class?

I'm having an issue with the document.querySelector in my JavaScript code. It currently only selects the first div that contains the class "test", but I need it to select all such divs. Is there a way to achieve this using my existing JavaScript? ...

What is the reason behind Visual Studio intellisense not displaying the methods of XMLHttpRequest objects?

Why am I unable to access the open and send methods of the XMLHttpRequest object in Visual Studio's Intellisense? var httprequest = new XMLHttpRequest(); httprequest. I cannot see the methods in Intellisense after the dot. ...

Executing a MongoDB query within a loop in a Node.js environment

I've been struggling to incorporate a nested DB query inside an eachOf loop that needs to be synchronous. Despite trying various combinations and methods, I haven't been successful with executing it inside the foreach loop. async.eachOf(nc.vi ...

Identify HTML elements within a textarea or text input using JavaScript while also accommodating the common special characters ">" and "<"

Is there a way to accurately detect HTML tags in textarea or text input fields before submitting a form? While it may seem straightforward to use regular expressions like /<\/?[^>]*>/gi.test(str) for this purpose, the challenge arises when de ...

Exploring geometric materials within the THREE.js framework

I'm currently working on creating a geometry in THREE.js: var dotGeometry = new THREE.Geometry(); dotGeometry.dynamic = true; var createDot = function (group, x, y, z){ group.vertices.push(new THREE.Vector3( x, y, z)); } var width = 300; var he ...

Tips on decorating multi-chain selection buttons

Our latest project involved implementing multi-select buttons. Due to the complexities of styling select and option tags, we decided to utilize chosen.js for this purpose. <link rel="stylesheet" href="$url_link/css/user_css/chosen.css"> <script t ...

A guide on breaking down a variable into an array using batch scripting

I am currently working on creating a text adventure game using batch scripting and I am looking for a way to split a variable like 'set userinput=take book' into an array. My goal is to develop a program that can divide strings into individual ar ...

Tips for making an interactive slider using JQuery

I need to create dynamic sliders within tabs that can change content dynamically. My development platform is ASP.NET MVC 5 and I'm using JSON data format. What's the best way to implement this dynamic slider feature for each tab? <div class ...

Mastering the correct way to handle the "window" object within the Node.js testing environment using JSDom

Testing my React app using Tape and JSDom involves importing a specific module at the beginning of each test JS file: import jsdom from 'jsdom' function setupDom() { if (typeof document === 'undefined') { global.document = jsdom ...

What is the process through which AngularJS retrieves a value from an asynchronous call?

Check out this video, https://www.youtube.com/watch?v=IRelx4-ISbs In the code, you'll notice a line that says: $scope.twitterResult = $scope.twitter.get({q:$scope.searchTerm}); It seems strange: the 'get' method of 'twitter' is ...

Import data from JSON using JavaScript

I have a collection of txt files that contain custom content. The file names are stored in a JSON array. { txtFiles: ['./file1.txt', './file2.txt', './file3.txt'] } I am looking to use the require function in JavaScript t ...

Utilizing Vue.js pagination and table sorting with Element components

I am currently working on a project using Vue js, Element Plus Table, and Pagination. The issue I am facing is that all columns of the table are sortable, but the sorting only works on the current page. I need to be able to sort all my data across multiple ...

Output a message to the Java console once my Selenium-created Javascript callback is triggered

My journey with Javascript has led me to mastering callback functions and grasping the concept of 'functional programming'. However, as a newcomer to the language, I struggle to test my syntax within my IntelliJ IDE. Specifically, I am working on ...