Filter array of strings

2

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

Example:

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

nomes.filter(item => ???);
    
asked by anonymous 19.04.2018 / 01:59

3 answers

0

You can use the .includes() method in the filter . This method has been implemented in 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

    
19.04.2018 / 02:29
0

Assuming the surname is the last name, you can split the names with split(" ") and get the last one with slice(-1) and check if it'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 split and slice

    
19.04.2018 / 02:06
0

If you want to use regular expressions , here's an example of how 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:

19.04.2018 / 02:13