By ErikRobles
Hello. If I wanted to filter an array and return only strings that contain the string ’ de ', How can I do that? I have the following but it only returns me the contents of the entire array:
let de = 'de ';
let newArr = streets.filter((street) => (street, de));
console.log(newArr);
Any help on this would be super. Thank you.
the array is as follows:
const streets = [
'Boulevards of Paris',
'City walls of Paris',
'Thiers wall',
'Wall of Charles V',
'Wall of Philip II Augustus',
'City gates of Paris',
"Haussmann's renovation of Paris",
'Boulevards of the Marshals',
'Boulevard Auguste-Blanqui',
'Boulevard Barbès',
'Boulevard Beaumarchais',
"Boulevard de l'Amiral-Bruix",
'Boulevard Mortier',
'Boulevard Poniatowski',
'Boulevard Soult',
'Boulevard des Capucines',
'Boulevard de la Chapelle',
'Boulevard de Clichy',
'Boulevard du Crime',
"Boulevard du Général-d'Armée-Jean-Simon",
'Boulevard Haussmann',
"Boulevard de l'Hôpital",
'Boulevard des Italiens',
'Boulevard Lefebvre',
'Boulevard de la Madeleine',
'Boulevard de Magenta',
'Boulevard Malesherbes',
'Boulevard Marguerite-de-Rochechouart',
'Boulevard Montmartre',
'Boulevard du Montparnasse',
'Boulevard Raspail',
'Boulevard Richard-Lenoir',
'Boulevard Saint-Germain',
'Boulevard Saint-Michel',
'Boulevard de Sébastopol',
'Boulevard de Strasbourg',
'Boulevard du Temple',
'Boulevard Voltaire',
'Boulevard de la Zone',
];
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Hi @ErikRobles,
There are multiple ways to do so but here is how I’ll do it:
const substring = 'de';
const matches = streets.filter(element => {
if (element.indexOf(substring) !== -1) {
return true;
} });
console.log(matches);
The function passed to the streets.filter method gets invoked with each element in the array, regardless if the condition is satisfied.
This is useful in case you have multiple elements in the array that satisfy the condition and you need all of their values.
In the if statement we’ve used the String.indexOf method. If the substring is contained in the string, the method returns the index of the match. If it isn’t, the method returns -1.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.