Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

244
Vistas
Filtering array with multiple conditions (javascript/typescript)?

Right now I have an array of objects

array = [
{
text: 'Example 1',
colorCode: '1'
},
{
text: 'Example 2',
colorCode: '2'
},
{
text: 'Example 3',
colorCode: '3'
}, 
text: 'Example 4',
colorCode: '3'
}
]

then I have an array of filters

filters = [1, 3]

I'm attempting to write a function that returns an array based on the filters provided so this example would return an array of objects containing example 1, example 2, and example 4.

Currently I'm creating an array and looping through the filters one at a time. Something like this

let filteredArray = [];
filters.forEach((x: number) => {  
        filteredArray = filteredArray.concat(_.filter(this.array, {colorCode: x}))
 })

However this seems redundant as I have to loop through the array for each filter, and will take more time as the array grows. I loop through the array and find all colorCode === 1, then loop through the array and find all colorCode === 3. Is there a way for me to only loop through the array one time and checking if each object.colorCode === 1 || object.colorCode === 3.

My problem with this function is that filters array are constantly changing in values and size, so the function needs to account for that rather than static values being passed.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use filter to remove the items whose colorCode property is not included in the filters array..

let array=[{text:"Example 1",colorCode:"1"},{text:"Example 2",colorCode:"2"},{text:"Example 3",colorCode:"3"},{text:"Example 4",colorCode:"3"}];

const filters = [1, 3]

let result = array.filter(e => filters.includes(+e.colorCode))
console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can start off with the colorCode values, filter per each value, then flatten the resulting array.

const array=[{text:"Example 1",colorCode:"1"},{text:"Example 2",colorCode:"2"},{text:"Example 3",colorCode:"3"},{text:"Example 4",colorCode:"3"}];

const filters = [1, 3]

const result = [].concat( ...filters.map(f => array.filter(({colorCode:c}) => +c === f)) );
console.log( result );

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda