javascript arrays filter

filtrar una matriz de objetos basada en otra matriz en javascript



arrays filter (9)

Tengo una gran variedad de objetos

people = [ {id: "1", name: "abc", gender: "m", age:"15" }, {id: "2", name: "a", gender: "m", age:"25" }, {id: "3", name: "efg", gender: "f", age:"5" }, {id: "4", name: "hjk", gender: "m", age:"35" }, {id: "5", name: "ikly", gender: "m", age:"41" }, {id: "6", name: "ert", gender: "f", age:" 30" }, {id: "7", name: "qwe", gender: "f", age:" 31" }, {id: "8", name: "bdd", gender: "m", age:" 78" }, ]

Tengo otra matriz:

id_filter = [1,4,5,8]

Quiero filtrar la matriz de personas si la id coincide con cualquiera de los elementos en la matriz id_filter y gender = m

¿Cómo hago esto en JavaScript usando la función de filtro?


Con la función Array.includes() :

var people = [ {id : "1", name : "abc", gender : "m", age :"15" }, {id : "2", name : "a", gender : "m", age :"25" }, {id : "3", name : "efg", gender : "f", age :"5" }, {id : "4", name : "hjk", gender : "m", age :"35" }, {id : "5", name : "ikly", gender : "m", age :"41" }, {id : "6", name : "ert", gender : "f", age :" 30" }, {id : "7", name : "qwe", gender : "f", age :" 31" }, {id : "8", name : "bdd", gender : "m", age :" 78" } ], id_filter = [1,4,5,8], result = people.filter((o) => id_filter.includes(+o.id) && o.gender == "m"); console.log(result);

  • +o.id - + se usa aquí para convertir una cadena numérica en número

La forma más sencilla de filtrar es usar la función de array.filter() JavaScript, similar a esto:

people.filter((person) => id_filter.includes(person.id))


Para este caso, puede utilizar el filtro e incluir la función, ya que sus ID son cadenas, debe analizarse antes de su uso.

var result = people.filter((person) => (id_filter.includes(parseInt(person.id)) && person.gender ===''m''))


Puede lograr eso con el siguiente código:

var filtered_people = people.filter(function(person){ return id_filter.includes(person.id) && person.gender === ''m''; });

Solo asegúrese de que la identificación de cada persona sea un número entero y no una cadena, como en su ejemplo. De lo contrario, la función include () no coincidirá. Además, su matriz de people tiene problemas internos de sintaxis. Entonces, el código final se vería así:

var people = [ {id: 1, name: "abc", gender: "m", age:15}, {id: 2, name: "a", gender: "m", age: 25}, {id: 3, name: "efg", gender: "f", age: 5}, {id: 4, name: "hjk", gender: "f", age: 35}, {id: 5, name: "ikly", gender: "m", age: 41}, {id: 6, name: "ert", gender: "f", age: 30}, {id: 7, name: "qwe", gender: "f", age: 31}, {id: 8, name: "bdd", gender: "m", age: 78} ]; var id_filter = [1,4,5,8]; var filtered_people = people.filter(function(person){ return id_filter.includes(person.id) && person.gender === ''m''; });

Espero que esto te ayude. Buena suerte.


Puede usar Array.prototype.filter como:

function filter(arr, ids, gender) { // takes an array of people arr, an array of indexes ids, and a gender and return the matched people objects from arr return arr.filter(function(obj) { // filtering each object... return ids.includes(obj.id) && obj.gender === gender; // if this object is is included in the ids array and if its gender property is equal to the desired gender }); } var people = [{id:"1",name:"abc",gender:"m",age:"15"},{id:"2",name:"a",gender:"m",age:"25"},{id:"3",name:"efg",gender:"f",age:"5"},{id:"4",name:"hjk",gender:"m",age:"35"},{id:"5",name:"ikly",gender:"m",age:"41"},{id:"6",name:"ert",gender:"f",age:"30"},{id:"7",name:"qwe",gender:"f",age:"31"},{id:"8",name:"bdd",gender:"m",age:"78"}]; console.log(filter(people, ["5", "7", "4"], "m")); // filtering elements where id is one of ["5", "7", "4"] and the gender is "m".

Nota: La propiedad de id de los objetos en las people son cadenas, por lo que debe proporcionar una matriz de identificadores de cadena para filter o convertir la propiedad de id en un número antes de pasarlo a includes .


Puede usar array.filter() con pocas condiciones para obtener el resultado que desea. También he corregido tu JSON.

var filtered = people.filter(function(item) { return id_filter.indexOf(item.id) !== -1 && item.gender===''m''; });

MANIFESTACIÓN

var people =[ { "id": 1, "name": "abc", "gender": "m","age": "15" }, { "id": 2, "name": "a", "gender": "m", "age": "25" }, { "id": 3,"name": "efg", "gender": "f","age": "5" }, { "id": 4,"name": "hjk","gender": "m","age": "35" }, { "id": 5, "name": "ikly","gender": "m","age": "41" }, { "id": 6, "name": "ert", "gender": "f", "age": "30" }, { "id": 7, "name": "qwe", "gender": "f", "age": "31" }, { "id":8, "name": "bdd", "gender": "m", "age": " 8" } ]; var id_filter = [1,4,5,8]; var filtered = people.filter(function(item) { return id_filter.indexOf(item.id) !== -1 && item.gender===''m''; }); console.log(filtered);


en este caso, tiene más sentido hacerlo a pie, así que primero debe iterar a través de su matriz de people luego verificar si una identificación de personas es igual a su lista de filtros

for(person in people) { for(id in id_filter) { if(person[id] == id && person[gender] == "m"){ } } }


const people = [ {id: "1", name: "abc", gender: "m", age: "15" }, {id: "2", name: "a", gender: "m", age: "25" }, {id: "3", name: "efg", gender: "f", age: "5" }, {id: "4", name: "hjk", gender: "m", age: "35" }, {id: "5", name: "ikly", gender: "m", age: "41" }, {id: "6", name: "ert", gender: "f", age: " 30" }, {id: "7", name: "qwe", gender: "f", age: " 31" }, {id: "8", name: "bdd", gender: "m", age: " 78" }, ] const idFilter = [1,4,5,8] const idIsInList = id => idFilter.includes(+id) // "+id" to make sure it is a number, not a string const genderIsMale = gender => gender === "m" const result = people.filter(item => idIsInList(item.id) && genderIsMale(item.gender)) console.log(result)


people = [ {id : "1", name : "abc", gender : "m", age :"15" }, {id : "2", name : "a", gender : "m", age :"25" }, {id : "3", name : "efg", gender : "f", age :"5" }, {id : "4", name : "hjk", gender : "m", age :"35" }, {id : "5", name : "ikly", gender : "m", age :"41" }, {id : "6", name : "ert", gender : "f", age :" 30" }, {id : "7", name : "qwe", gender : "f", age :" 31" }, {id : "8", name : "bdd", gender : "m", age :" 78" } ] var id_filter = ["1","4","5","8"], filteredPeople = []; for( var i=people.length-1; i>=0; --i){ if( id_filter.indexOf( people[i].id ) != -1 ){ filteredPeople.push( people[i] ); } } console.log( filteredPeople );