user3180997
user3180997

Reputation: 1926

Loop through array and filter emails

I am trying to filter our values from an array depending on what the users email is.

An example is, I have an array that looks like:

var myArray = ["[email protected]","[email protected]","[email protected]","[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"];

I am trying to push only the values that end in the following email addresses:

  1. *@hotmail.com
  2. *@gmail.com

I would like to filter out ALL other email addresses. So it only returns the email addresses where the addresses matches the values above.

I have come up with the following code:

var filteredArray = [];

for (var i = 0, l = myJson.length; i < l; i++) {
  /// Don't know what to put here!
  filteredArray.push();
}

I would like to push the desired values to the filteredArray. All the other values like: @yahhoo.com & @test.com & @email.com I do not need.

I think I am in the starting position but don't know how to loop through and filter based on part of a string. Thanks.

Upvotes: 0

Views: 1497

Answers (3)

Gavin
Gavin

Reputation: 4515

You can use Array.prototype.filter(). It returns a new array with the values that would cause the callback function to return true.

var myArray = ["[email protected]","[email protected]","[email protected]","[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"];

var filtered = myArray.filter(function(email) {
  return email.endsWith('@hotmail.com') || email.endsWith('@gmail.com');
});

console.log(filtered);

Upvotes: 4

Sterling Archer
Sterling Archer

Reputation: 22405

You can use an ES6 function includes with the filter function to achieve this.

let fitleredEmails = myJson.filter(index => index.includes("@gmail.com") || index.includes("@hotmail.com"));

Upvotes: 2

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38817

var filteredArray = myArray.filter(function(element) {
  return element.endsWith('@hotmail.com') || element.endsWith('@gmail.com');
});

Upvotes: 1

Related Questions