What is the best method to delete an element from an array that contains specific characters?

I am looking to filter out specific values from an array.

var array = [<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2149444d4d4e615840494e4e0f424e4c">[email protected]</a>, www.hello.com, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b333e3737341b3c363a323775383436">[email protected]</a>];

I need to remove any element in the array that includes an @ sign. For example, I should only have www.hello.com when I display the alert.

Answer №1

Loop through each element in the array and check if it contains the "@" symbol. If it does, remove that element from the array.

Answer №2

It is advisable to avoid deleting or changing the index of elements in an array within a loop. This is because the array gets re-indexed when using .splice(), leading to the possibility of skipping over an index when an element is removed.

Instead, consider filtering out the elements to create a new array that meets your desired criteria.

var array = [
'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ff7faf3f3f0dfe6fef7f0f0b1fcf0f2">[email protected]</a>',
'www.hello.com',
'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f69e939a9a99b6919b979f9ad895999b">[email protected]</a>'];
var newArray = array.filter(function(item){  
    return item.indexOf('@') ==-1
})
console.log(newArray)

Check out the DEMO here.

Answer №3

If you're looking to achieve this task, one method is to utilize a Regular Expression in combination with a second array. Here's an example:

var array = ['<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3cbc6cfcfcce3dac2cbcccc8dc0ccce">[email protected]</a>', 'www.hello.com', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83ebe6efefecc3e4eee2eaefade0ecee">[email protected]</a>'];
var array2 = [];
for (var i = 0; i < array.length; i++) {
  if (!(/@/.test(array[i]))) {
    array2.push(array[i]);
  };
};
alert(array2);

Answer №4

One way to filter elements from an input array is to use a loop and push matching elements into a new output array.

var array = [
'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="157d7079797a556c747d7a7a3b767a78">[email protected]</a>',
'www.hello.com',
'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6ded3dadad9f6d1dbd7dfda98d5d9db">[email protected]</a>'];
var newArray = [];
array.forEach(x => { 
  if(x.indexOf('@') === -1) 
     newArray.push(x);
});
console.log(newArray)

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

Is there a way for me to retrieve the initial element from this array?

The variable blobstream holds the following array: blobstream = [1,2,3] My requirement is to only retrieve one array element per loop iteration: first loop: 1 second loop: 2 third loop: 3 Can anyone suggest the most efficient approach for achieving this? ...

Is it possible to retrieve the IMEI number of a mobile phone using expo?

Currently working on developing a mobile app with React Native using Expo. I need to figure out a way to access the client's mobile IMEI number and display it in the front end of the app. Unsure of how to accomplish this task. Is there a method to do ...

If the number exceeds 1, then proceed with this action

I currently have a variable called countTicked, which holds an integer representing the number of relatedBoxes present on the page. I am in need of an if statement that will perform certain actions when the value stored in countTicked exceeds 1. if (!$(c ...

Commitment and the worth of pointing

I am trying to create a promise chain in Angular to execute a series of queries: for(variableIndex in _editableVariable.values) { var v = _editableVariable.values[variableIndex]; if(v.value != v.old_value) { ...

Navigating through multiple pages with React Native stack navigation

I'm currently in the process of developing a react native app and I'm facing some confusion with regards to page navigation. It appears that there is a glitch in the navigation flow, causing it to skip a page. <NavigationContainer> ...

React Native Function fails to return a value

Within my React Native app, there's a page called RepsPage that displays a scroll view using an array of IDs. I'm passing this array to a function named renderRep, attempting to create a view for each item in the array. However, the return statem ...

What could be causing the issue with the array.push method not functioning

i have come across this piece of code function fetchImagesList(errU,errorsList) { if(errU) throw errU; var directories=new Array(); var sourceDir=''; var destinationDir=''; if(errorsList==&a ...

Eliminating unnecessary CSS from the codebase of a website

Currently, I am making adjustments to a website template that I downloaded for free online. I have noticed that even if I delete a div from the code, the corresponding CSS styles remain in one or more files. Is there any tool available that can automatic ...

Error: A TypeError occurred with the startup because it was unable to read the property 'Collection' as it was

Recently, I encountered a series of problems one after another. The first issue was: TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client To resolve this problem, I made changes to my code from: const Discord = require(" ...

What steps do I need to take to successfully integrate Font Awesome 5 with React?

Here is an interesting scenario: the initial icon is displayed, but it fails to update when the class changes. const Circle = ({ filled, onClick }) => { const className = filled ? 'fas fa-circle' : 'far fa-circle'; return ( ...

Updating the state in React can be achieved by using the `

Upon obtaining a list of search results, each result is equipped with an onclick function. My goal is to exhibit the user-selected results on the screen by adding them to an array upon click: let selectedData = [] function addFunc(resultdata){ consol ...

Exploring the world of promise testing with Jasmine Node for Javascript

I am exploring promises testing with jasmine node. Despite my test running, it indicates that there are no assertions. I have included my code below - can anyone spot the issue? The 'then' part of the code is functioning correctly, as evidenced b ...

Exploring jQuery to compare and distinguish the variances within 2 JSON arrays

Looking for help with comparing elements in two JSON arrays using jQuery? Specifically, I want to compare elements (a,b) from array1 against array2 and identify any differences. Here's the code I've tried so far, but it's giving unexpected o ...

creating a custom mongoose model using aggregation and filtering

My Review model includes two fields, product and rating. I want to calculate the total rating for a specific product and then find the average by dividing that total by 5. const mongoose = require('mongoose'); const ReviewSchema = mongoose.Sche ...

What is the best way to organize tableview cells into alphabetical sections with a customized header cell?

In my CartVC, I have data being passed from another ViewController through a closure to populate the cells successfully. Now, I am attempting to organize these cells into sections based on their brand in the CartVC. However, all the data seems to be gettin ...

Learn how to automatically retrieve messages without refreshing the page by leveraging the power of AJAX

displaying notifications with:- $call = "SELECT * FROM `chat` WHERE fromthe = '$email' and tothe='theadmin' UNION ALL SELECT * FROM `chat` WHERE fromthe = 'theadmin' and tothe='$email' order by id desc"; mysqli_quer ...

Retrieve all the keys from an array of objects that contain values in the form of arrays

Looking for an efficient way to extract all keys from an array of objects whose values are arrays, without any duplicates. I want to achieve this using pure JavaScript, without relying on libraries like lodash or underscore. Any suggestions on how to impro ...

pressing the switch will adjust the size of the container

I am looking to implement a feature where clicking on an icon will resize a div to full screen in the browser. Below is the HTML code I have set up for this functionality, and I am open to suggestions on how to achieve this. <div> <a (click)= ...

Vue.js is displaying an error message stating that the data property is

I am struggling to access my data property within my Vue.js component. It seems like I might be overlooking something obvious. Below is a condensed version of my code. The file StoreFilter.vue serves as a wrapper for the library matfish2/vue-tables-2. &l ...

The issue with the jQuery class change not being triggered in Internet Explorer seems to be isolated, as Chrome and

This little jQuery script I have is supposed to show a fixed navigation menu once the page has been scrolled below 200px, and then change the class on each menu list item to "current" when that section reaches the top of the viewport. The issue is that th ...