Filter array of objects based on another array in javascript
Asked Answered
E

10

79

Given an array of objects :

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" },
]

And an array of wanted ids:

id_filter = [1,4,5,8]

How to filter array people to return the target ids defined in id_filter and of gender=m ?

Euler answered 23/10, 2017 at 16:38 Comment(1)
Please use either const or let to declare variables, for example const people = [].Triny
L
95

The simplest way to filter is to use the array's filter() function, similar to this:

people.filter(person => id_filter.includes(person.id))
Lymphangitis answered 23/10, 2017 at 16:45 Comment(3)
what if i want to add another condition that gender should be == m ?Euler
people.filter((person) => person.gender == 'm')Lymphangitis
It would really be people.filter((person) => id_filter.includes(Number(person.id)) && person.gender === "m") or people.filter(({ id, gender }) => id_filter.includes(Number(id)) && gender === "m").Shaunshauna
N
25

You can use array.filter() with few conditions to get the output you want. Also i have corrected your JSON.

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

DEMO

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);
Nitpicking answered 23/10, 2017 at 16:50 Comment(0)
H
11

With Array.includes() function:

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 - + is used here to cast a numeric string into number
Hayfork answered 23/10, 2017 at 16:47 Comment(0)
B
4

You can achieve that by the following code:

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

Just make sure the id for each person is an integer and not an string, as in your example. Otherwise, the includes() function won't match. Also, your people array has internal syntax problems. So, the final code would look like this:

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: "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}
]
const id_filter = [1,4,5,8]
const filtered_people = people.filter((person) => id_filter.includes(person.id) && person.gender === 'm')
console.log(filtered_people)

I hope this helps you. Good luck.

Barong answered 23/10, 2017 at 16:52 Comment(0)
L
2

For this case you can make use of filter and include function, since you id's are string,it need to be parse before use.

var result = people.filter((person) => (id_filter.includes(parseInt(person.id)) && person.gender ==='m'))
Leotaleotard answered 6/3, 2019 at 9:22 Comment(0)
T
1

in this case it makes more sense to do this by foot so first you need to iterate through your people array then you check if a persons id is equal to your filter list

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

         }
     }
}
Typeset answered 23/10, 2017 at 16:41 Comment(1)
I want a filtered array and also the ids are not in serial. also another condition needs to be added that gender is = mEuler
S
1

You can use Array.prototype.filter like:

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".

Note: The id property of the objects in people are strings so you have to either provides an array of string ids to filter or convert the id property to a number before passing it to includes.

Supramolecular answered 23/10, 2017 at 16:48 Comment(0)
O
1

If your id_filter is large, you would want to first convert it to a new Set(). This will allow for constant-time lookup. You can then iterate your people array using .filter() and return true if your set .has() the id in it and if the gender is equal to '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 id_filter = new Set([1,4,5,8]);
const res = people.filter(({id, gender}) => id_filter.has(+id) && gender === 'm');
console.log(res);

Overall, the time complexity for this approach will be O(N + k) as opposed to the O(Nk) you would get if you were using the .includes() or .indexOf() approach, where N is the length of the people array, and k is the length of the id_filter array

Olsen answered 15/12, 2019 at 9:33 Comment(0)
T
0

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)
Triny answered 23/10, 2017 at 16:48 Comment(0)
R
-1

    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 );
Remount answered 23/10, 2017 at 16:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.