Filter string array

Asked

Viewed 801 times

2

How do I go through an array of names using the javascript filter function where the return is just people’s names with the surname "Carvalho"?

Example:

let nomes = ["Thiago Carvalho", "Renata Carvalho", "Alexandre Otoni", "Guilherme Otoni de Carvalho"];

nomes.filter(item => ???);

3 answers

1


You can use the method .includes() in the filter. This method has been implemented in the Ecmascript 2015 (ES6), and works similar to the old indexOf:

let nomes = ["Thiago Carvalho", "Renata Carvalho", "Alexandre Otoni", "Guilherme Otoni de Carvalho"];
let filtro = nomes.filter(item => item.includes("Carvalho"));
console.log(filtro);

DOCUMENTATION

  • Thank you, it was just the solution I was looking for!

0

Assuming the last name is the last name, you can divide the names with split(" ") and get the last with slice(-1) and check if that’s what you want:

let nomes = ["Thiago Carvalho", "Renata Carvalho", "Alexandre Otoni", "Guilherme Otoni de Carvalho"];

let filtro = "Carvalho";
let nomesFiltrados = nomes.filter(item => item.split(" ").slice(-1) == filtro);
console.log(nomesFiltrados);

Documentation for the split and slice

0

If you want to use regular expressions, I leave here an example of how to do it:

const nomes = ['Thiago Carvalho', 'Renata Carvalho', 'Alexandre Otoni', 'Guilherme Otoni de Carvalho'];

const filtro = 'Carvalho';
const nomesFiltrados = nomes.filter(item => (new RegExp(filtro)).test(item));

console.log(nomesFiltrados);

Documentation for the methods used:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.