recorrer objetos objeto lista eliminar elemento buscar array agregar javascript arrays filter

lista - Filtrar objetos javascript con otra matriz



map javascript (3)

Tengo Javascript array de objetos como este

var posts = [ {area: ''NY'', name: ''Bla'', ads: true}, {area: ''DF'', name: ''SFS'', ads: false}, {area: ''TT'', name: ''SDSD'', ads: true}, {area: ''SD'', name: ''Engine'', ads: false}, {area: ''NSK'', name: ''Toyota'', ads: false}, ];

y otra colección de filtros como esta

var filter = [''NY'', ''SD''];

Estoy tratando de filtrar mi matriz de posts con este filtro

function filtered() { return posts .filter(function(post){ return post.ads === true; }) .filter(function(post){ return filter.indexOf(post.area) > 0; }) } console.log(filtered());

y este filtro no da nada, solo matriz vacía

Por favor revisa jsfiddle


Este es un caso de uso típico para Array.prototype.filter() y Array.prototype.some() combo.

var posts = [ {area: ''NY'', name: ''Bla'', ads: true}, {area: ''DF'', name: ''SFS'', ads: false}, {area: ''TT'', name: ''SDSD'', ads: true}, {area: ''SD'', name: ''Engine'', ads: false}, {area: ''NSK'', name: ''Toyota'', ads: false}, ], filter = [''NY'', ''SD'']; result = posts.filter(o => filter.some(f => o.ads && f === o.area)); console.log(result); // or with filter & includes combo result = posts.filter(o => o.ads && filter.includes(o.area)); console.log(result);


Podría usar una solución más genérica con restricciones para el filtrado.

function filter(array, constraints) { return array.filter(function(a) { return Object.keys(constraints).every(function(k) { return typeof constraints[k] === ''function'' ? constraints[k](a[k]) : a[k] === constraints[k] ; }); }); } var posts = [{ area: ''NY'', name: ''Bla'', ads: true }, { rea: ''DF'', name: ''SFS'', ads: false }, { area: ''TT'', name: ''SDSD'', ads: true }, { rea: ''SD'', name: ''Engine'', ads: false }, { area: ''NSK'', ame: ''Toyota'', ads: false }], result = filter(posts, { ads: true, area: function (v) { return [''NY'', ''SD''].indexOf(v) !== -1; } }); console.log(result);


Solo se necesita Array#filter método de Array#filter único Array#filter y la segunda condición debe ser indexOf(post.area) > -1; ya que el índice comienza desde 0 .

var posts = [ {area: ''NY'', name: ''Bla'', ads: true}, {area: ''DF'', name: ''SFS'', ads: false}, {area: ''TT'', name: ''SDSD'', ads: true}, {area: ''SD'', name: ''Engine'', ads: false}, {area: ''NSK'', name: ''Toyota'', ads: false}, ]; var filter = [''NY'', ''SD'']; function filtered(p, f) { return p .filter(function(v) { return v.ads && f.indexOf(v.area) > -1; }) } console.log(filtered(posts, filter));