'Properly filter names on an array in java

so I have this data on an array and I need to only appear [ {apellido_paterno:"algo",nombre: "jose"} ] in the output but its showing all 3 of the objects

let data = [{nombre: 'joselyn',apellido_paterno:'poblete'},
{nombre:'jose',apellido_paterno:'algo'},
{nombre:'ernesto',apellido_paterno:'joseludo'}]
const filtro = 'jose'

data = data.filter((row) =>{
  const nombreCompleto = `${row.nombre}${row.apellido_paterno}`.toLowerCase()
  const nombreCompletoReves = `${row.apellido_paterno}${row.nombre}`.toLowerCase()
  const nombreTrimmed = filtro.replace(/\s+/g, '').toLowerCase()
  return nombreCompleto.includes(nombreTrimmed) || nombreCompletoReves.includes(nombreTrimmed);
})

console.log(data) 
// expected output  [{apellido_paterno:"algo",nombre: "jose"}]
// output [{apellido_paterno: "poblete",nombre: "joselyn"},{apellido_paterno:"algo",nombre: "jose"},
// {apellido_paterno: "joseludo",nombre: "ernesto"}]


Solution 1:[1]

If I understand correctly, you want to filter the object where nombre is jose. You can just .filter() on data. Like this

let data = [{
    nombre: 'joselyn',
    apellido_paterno: 'poblete'
  },
  {
    nombre: 'jose',
    apellido_paterno: 'algo'
  },
  {
    nombre: 'ernesto',
    apellido_paterno: 'joseludo'
  }
]
const filtro = 'jose'

data = data.filter(x => x.nombre == filtro);

console.log(data)

Solution 2:[2]

Here is the working code

let data = [
  { nombre: "joselyn", apellido_paterno: "poblete" },
  { nombre: "jose", apellido_paterno: "algo" },
  { nombre: "ernesto", apellido_paterno: "joseludo" },
  // line added by me to demonstrate the first example
  { nombre: "javier", apellido_paterno: "jose rodrigo" }
];
const filtro = "jose";

console.log("filtro wrapped by spaces in any part of row.nombre or row.apellido_paterno",
  data.filter(row => 
    (row.nombre + " " + row.apellido_paterno)
      .toLowerCase()
      .split(" ")
      .includes(filtro)
  )
);

console.log("filtro strictly matches row.nombre or row.apellido_paterno",
  data.filter(row => 
    row.nombre == filtro ||
    row.apellido_paterno == filtro
  )
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shivam
Solution 2