148

I want to simplify an array of objects. Let's assume that I have following array:

var users = [{
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    address: 'USA'
    },
    {
        name: 'Tom',
        email: 'tom@mail.com',
        age: 35,
        address: 'England'
    },
    {
        name: 'Mark',
        email: 'mark@mail.com',
        age: 28,
        address: 'England'
}];

And filter object:

var filter = {address: 'England', name: 'Mark'};

For example i need to filter all users by address and name, so i do loop through filter object properties and check it out:

function filterUsers (users, filter) {
    var result = [];
    for (var prop in filter) {
        if (filter.hasOwnProperty(prop)) {

            //at the first iteration prop will be address
            for (var i = 0; i < filter.length; i++) {
                if (users[i][prop] === filter[prop]) {
                    result.push(users[i]);
                }
            }
        }
    }
    return result;
}

So during first iteration when prop - address will be equal 'England' two users will be added to array result (with name Tom and Mark), but on the second iteration when prop name will be equal Mark only the last user should be added to array result, but i end up with two elements in array.

I have got a little idea as why is it happening but still stuck on it and could not find a good solution to fix it. Any help is appreciable. Thanks.

Prerna Jain
  • 1,240
  • 2
  • 16
  • 34
user3673623
  • 1,795
  • 2
  • 12
  • 18

29 Answers29

174

You can do like this

var filter = {
  address: 'England',
  name: 'Mark'
};
var users = [{
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    address: 'USA'
  },
  {
    name: 'Tom',
    email: 'tom@mail.com',
    age: 35,
    address: 'England'
  },
  {
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    address: 'England'
  }
];


users= users.filter(function(item) {
  for (var key in filter) {
    if (item[key] === undefined || item[key] != filter[key])
      return false;
  }
  return true;
});

console.log(users)
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Raghavendra
  • 3,530
  • 1
  • 17
  • 18
  • 1
    this is good one but actually im getting Uncaught ReferenceError: filter is not defined – Leandro Bardelli Nov 12 '16 at 00:58
  • 6
    You should choose a different name for your filter variable. It's a bad coding practice to give your variables protected names. Especially since you end up using that protected name a few lines later to call the Array.prototype.filter method. – Nadav Sep 21 '18 at 08:05
  • Great answer. What about when you want to filter based on an multiple criteria, such as: var filter_address = ['England', 'UK']; var filter_name = ['Tom', 'Anne']; ? – andrussk Jun 06 '19 at 11:54
  • 1
    @andrussk var country = ["England", "UK"], names = ["Tom", "Anne"]; users.filter(el => (country.indexOf(el.address) >= 0 && names.indexOf(el.name) >=0 ) ); – Anuj Srivastava Jun 14 '19 at 16:33
  • 1
    What if the filter condition is an array? – Arj 1411 Oct 28 '20 at 12:13
  • 1
    How would you do it, if you want to check multiple values like so: ```var filter = { address: ['England', 'Spain', 'Italy'], name: ['Mark', 'Pablo'] };``` – Vorname Nachname Dec 24 '21 at 18:15
  • It worked for me!. But if I'm doing exact same logic using Object.keys().map() then it is returning an empty array!. By the way, Thanks for the answer! – Ahmed Shaikh Feb 24 '22 at 14:06
94

If you know the name of the filters, you can do it in a line.

users = users.filter(obj => obj.name == filter.name && obj.address == filter.address)
Abhishek Chandran
  • 1,536
  • 1
  • 13
  • 21
30

Another take for those of you that enjoy succinct code.

NOTE: The FILTER method can take an additional this argument, then using an E6 arrow function we can reuse the correct this to get a nice one-liner.

var users = [{name: 'John',email: 'johnson@mail.com',age: 25,address: 'USA'},
             {name: 'Tom',email: 'tom@mail.com',age: 35,address: 'England'},
             {name: 'Mark',email: 'mark@mail.com',age: 28,address: 'England'}];

var query = {address: "England", name: "Mark"};

var result = users.filter(search, query);

function search(user){
  return Object.keys(this).every((key) => user[key] === this[key]);
}




// |----------------------- Code for displaying results -----------------|
var element = document.getElementById('result');

function createMarkUp(data){
  Object.keys(query).forEach(function(key){
    var p = document.createElement('p');
    p.appendChild(document.createTextNode(
    key.toUpperCase() + ': ' + result[0][key]));
    element.appendChild(p);
  });
}

createMarkUp(result);
<div id="result"></div>
SoEzPz
  • 14,958
  • 8
  • 61
  • 64
17

Here is ES6 version of using arrow function in filter. Posting this as an answer because most of us are using ES6 these days and may help readers to do filter in advanced way using arrow function, let and const.

const filter = {
  address: 'England',
  name: 'Mark'
};
let users = [{
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    address: 'USA'
  },
  {
    name: 'Tom',
    email: 'tom@mail.com',
    age: 35,
    address: 'England'
  },
  {
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    address: 'England'
  }
];


users= users.filter(item => {
  for (let key in filter) {
    if (item[key] === undefined || item[key] != filter[key])
      return false;
  }
  return true;
});

console.log(users)
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
17
users.filter(o => o.address == 'England' && o.name == 'Mark')

Much better for es6. or you can use || (or) operator like this

users.filter(o => {return (o.address == 'England' || o.name == 'Mark')})
wahyu setiawan
  • 178
  • 2
  • 7
11

Using Array.Filter() with Arrow Functions we can achieve this using

users = users.filter(x => x.name == 'Mark' && x.address == 'England');

Here is the complete snippet

// initializing list of users
var users = [{
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    address: 'USA'
  },
  {
    name: 'Tom',
    email: 'tom@mail.com',
    age: 35,
    address: 'England'
  },
  {
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    address: 'England'
  }
];

//filtering the users array and saving 
//result back in users variable
users = users.filter(x => x.name == 'Mark' && x.address == 'England');


//logging out the result in console
console.log(users);
Hamza Khanzada
  • 1,439
  • 1
  • 22
  • 39
10

Can also be done this way:

    this.users = this.users.filter((item) => {
                return (item.name.toString().toLowerCase().indexOf(val.toLowerCase()) > -1 ||
                item.address.toLowerCase().indexOf(val.toLowerCase()) > -1 ||
                item.age.toLowerCase().indexOf(val.toLowerCase()) > -1 ||
                item.email.toLowerCase().indexOf(val.toLowerCase()) > -1);
            })
Diogo Rodrigues
  • 1,312
  • 15
  • 15
10

Improving on the good answers here, below is my solution:

const rawData = [
  { name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA' },
  { name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England' },
  { name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England' }
]
const filters = { address: 'England', age: 28 }

const filteredData = rawData.filter(i =>
  Object.entries(filters).every(([k, v]) => i[k] === v)
)
pmsoltani
  • 976
  • 8
  • 13
7

I think this might help.

const filters = ['a', 'b'];

const results = [
  {
    name: 'Result 1',
    category: ['a']
  },
  {
    name: 'Result 2',
    category: ['a', 'b']
  },
  {
    name: 'Result 3',
    category: ['c', 'a', 'b', 'd']
  }
];

const filteredResults = results.filter(item =>
  filters.every(val => item.category.indexOf(val) > -1)
);

console.log(filteredResults);
  
Coşkun Deniz
  • 2,049
  • 1
  • 14
  • 11
7

Dynamic filters with AND condition

Filter out people with gender = 'm'

var people = [
    {
        name: 'john',
        age: 10,
        gender: 'm'
    },
    {
        name: 'joseph',
        age: 12,
        gender: 'm'
    },
    {
        name: 'annie',
        age: 8,
        gender: 'f'
    }
]
var filters = {
    gender: 'm'
}

var out = people.filter(person => {
    return Object.keys(filters).every(filter => {
        return filters[filter] === person[filter]
    });
})


console.log(out)

Filter out people with gender = 'm' and name = 'joseph'

var people = [
    {
        name: 'john',
        age: 10,
        gender: 'm'
    },
    {
        name: 'joseph',
        age: 12,
        gender: 'm'
    },
    {
        name: 'annie',
        age: 8,
        gender: 'f'
    }
]
var filters = {
    gender: 'm',
    name: 'joseph'
}

var out = people.filter(person => {
    return Object.keys(filters).every(filter => {
        return filters[filter] === person[filter]
    });
})


console.log(out)

You can give as many filters as you want.

NIKHIL C M
  • 3,873
  • 2
  • 28
  • 35
4

In lodash,

_.filter(users,{address: 'England', name: 'Mark'})

In es6,

users.filter(o => o.address == 'England' && o.name == 'Mark')
3

You'll have more flexibility if you turn the values in your filter object into arrays:

var filter = {address: ['England'], name: ['Mark'] };

That way you can filter for things like "England" or "Scotland", meaning that results may include records for England, and for Scotland:

var filter = {address: ['England', 'Scotland'], name: ['Mark'] };

With that setup, your filtering function can be:

const applyFilter = (data, filter) => data.filter(obj =>
    Object.entries(filter).every(([prop, find]) => find.includes(obj[prop]))
);

// demo
var users = [{name: 'John',email: 'johnson@mail.com',age: 25,address: 'USA'},{name: 'Tom',email: 'tom@mail.com',age: 35,address: 'England'},{name: 'Mark',email: 'mark@mail.com',age: 28,address: 'England'}];var filter = {address: ['England'], name: ['Mark'] };
var filter = {address: ['England'], name: ['Mark'] };

console.log(applyFilter(users, filter));
trincot
  • 317,000
  • 35
  • 244
  • 286
3

If you want to put multiple conditions in filter, you can use && and || operator.

var product= Object.values(arr_products).filter(x => x.Status==status && x.email==user)
R15
  • 13,982
  • 14
  • 97
  • 173
3

A clean and functional solution

const combineFilters = (...filters) => (item) => {
    return filters.map((filter) => filter(item)).every((x) => x === true);
};

then you use it like so:

const filteredArray = arr.filter(combineFilters(filterFunc1, filterFunc2));

and filterFunc1 for example might look like this:

const filterFunc1 = (item) => {
  return item === 1 ? true : false;
};
3

We can use different operators to provide multiple condtion to filter the array in the following way

Useing OR (||) Operator:

const orFilter = [{a:1, b: 3}, {a:1,b:2}, {a: 2, b:2}].filter(d => (d.a !== 1 || d.b !== 2))
console.log(orFilter, 'orFilter')

Using AND (&&) Operator:

const andFilter = [{a:1, b: 3}, {a:1,b:2}, {a: 2, b:2}].filter(d => (d.a !== 1 && d.b !== 2))
console.log(andFilter, 'andFilter')
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
1

functional solution

function applyFilters(data, filters) {
  return data.filter(item =>
    Object.keys(filters)
      .map(keyToFilterOn =>
        item[keyToFilterOn].includes(filters[keyToFilterOn]),
      )
      .reduce((x, y) => x && y, true),
  );
}

this should do the job

applyFilters(users, filter);

1

My solution, based on NIKHIL C M solution:

 let data = [
    { 
      key1: "valueA1", 
      key2: "valueA2",
      key3: []
    },{
      key1: "valueB1", 
      key2: "valueB2"
      key3: ["valuesB3"]
    }
 ];

 let filters = {
    key1: "valueB1",
    key2: "valueB2"
 };

 let filteredData = data.filter((item) => {
     return Object.entries(filters).every(([filter, value]) => {
          return item[filter] === value;
          //Here i am applying a bit more logic like 
          //return item[filter].includes(value) 
          //or filter with not exactly same key name like
          //return !isEmpty(item.key3)
     });
 });
Jose Velasco
  • 180
  • 2
  • 8
1

A question I was in the middle of answering got (properly) closed as duplicate of this. But I don't see any of the answers above quite like this one. So here's one more option.

We can write a simple function that takes a specification such as {name: 'mike', house: 'blue'}, and returns a function that will test if the value passed to it matches all the properties. It could be used like this:

const where = (spec, entries = Object .entries (spec)) => (x) =>
  entries .every (([k, v]) => x [k] == v)

const users = [{name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA'}, {name: 'Mark', email: 'marcus@mail.com', age: 25, address: 'USA'}, {name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England'}, {name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England'}]

console .log ('Mark', users .filter (where ({name: 'Mark'})))
console .log ('England', users .filter (where ({address: 'England'})))
console .log ('Mark/England', users .filter (where ({name: 'Mark', address: 'England'})))
.as-console-wrapper {max-height: 100% !important; top: 0}

And if we wanted to wrap the filtering into a single function, we could reuse that same function, wrapped up like this:

const where = (spec, entries = Object .entries (spec)) => (x) =>
  entries .every (([k, v]) => x [k] == v)

const filterBy = (spec) => (xs) => 
  xs .filter (where (spec))

const users = [{name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA'}, {name: 'Mark', email: 'marcus@mail.com', age: 25, address: 'USA'}, {name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England'}, {name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England'}]


console .log ('Mark/England', filterBy ({address: "England", name: "Mark"}) (users))
.as-console-wrapper {max-height: 100% !important; top: 0}

(Of course that last doesn't have to be curried. We could change that so that we could call it with two parameters at once. I find this more flexible, but YMMV.)

Keeping it as a separate function has the advantage that we could then reuse it, in say, a find or some other matching situation.


This design is very similar to the use of where in Ramda (disclaimer: I'm one of Ramda's authors.) Ramda offers the additional flexibility of allowing arbitrary predicates instead of values that have to be equal. So in Ramda, you might write something like this instead:

filter (where ({
  address: equals ('England')
  age: greaterThan (25)
}) (users)

It's much the same idea, only a bit more flexible.

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
0

If the finality of you code is to get the filtered user, I would invert the for to evaluate the user instead of reducing the result array during each iteration.

Here an (untested) example:

function filterUsers (users, filter) {
    var result = [];

    for (i=0;i<users.length;i++){
        for (var prop in filter) {
            if (users.hasOwnProperty(prop) && users[i][prop] === filter[prop]) {
                result.push(users[i]);
            }
        }
    }
    return result;
}
The_Black_Smurf
  • 5,178
  • 14
  • 52
  • 78
0

with the composition of some little helpers:

const filter = {address: 'England', name: 'Mark'};
console.log( 
  users.filter(and(map(propMatches)(filter)))
)

function propMatches<T>(property: string, value: any) {
  return (item: T): boolean => item[property] === value
}

function map<T>(mapper: (key: string, value: any, obj: T) => (item:T) => any) {
  return (obj: T) => {
    return Object.keys(obj).map((key) => {
      return mapper(key, obj[key], obj)
    });
  }
}

export function and<T>(predicates: ((item: T) => boolean)[]) {
  return (item: T) =>
    predicates.reduce(
        (acc: boolean, predicate: (item: T) => boolean) => {
            if (acc === undefined) {
                return !!predicate(item);
            }
            return !!predicate(item) && acc;
        },
        undefined // initial accumulator value
    );
}
nils petersohn
  • 2,317
  • 2
  • 25
  • 27
0

This is an easily understandable functional solution

let filtersObject = {
  address: "England",
  name: "Mark"
};

let users = [{
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    address: 'USA'
  },
  {
    name: 'Tom',
    email: 'tom@mail.com',
    age: 35,
    address: 'England'
  },
  {
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    address: 'England'
  }
];

function filterUsers(users, filtersObject) {
  //Loop through all key-value pairs in filtersObject
  Object.keys(filtersObject).forEach(function(key) {
    //Loop through users array checking each userObject
    users = users.filter(function(userObject) {
      //If userObject's key:value is same as filtersObject's key:value, they stay in users array
      return userObject[key] === filtersObject[key]
    })
  });
  return users;
}

//ES6
function filterUsersES(users, filtersObject) {
  for (let key in filtersObject) {
    users = users.filter((userObject) => userObject[key] === filtersObject[key]);
  }
  return users;
}

console.log(filterUsers(users, filtersObject));
console.log(filterUsersES(users, filtersObject));
Stax
  • 1
0

This is another method i figured out, where filteredUsers is a function that returns the sorted list of users.

var filtersample = {address: 'England', name: 'Mark'};

filteredUsers() {
  return this.users.filter((element) => {
    return element['address'].toLowerCase().match(this.filtersample['address'].toLowerCase()) || element['name'].toLowerCase().match(this.filtersample['name'].toLowerCase());
  })
}
0
const users = [{
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    address: 'USA'
  },
  {
    name: 'Tom',
    email: 'tom@mail.com',
    age: 35,
    address: 'England'
  },
  {
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    address: 'England'
  }
];

const filteredUsers = users.filter(({ name, age }) => name === 'Tom' && age === 35)

console.log(filteredUsers)

  • 1
    While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. – borchvm Aug 13 '20 at 11:41
0

Using lodash and not pure javascript

This is actually quite simple using lodash and very easy to add/modify filters.

import _ from 'lodash';

async getUsersWithFilter(filters) {
     const users = yourArrayOfSomethingReally();

    // Some properties of the 'filters' object can be null or undefined, so create a new object without those undefined properties and filter by those who are defined
    const filtersWithoutUndefinedValuesObject = _.omitBy(
      filters,
      _.isNil,
    );

    return _.filter(users, { ...filtersWithoutUndefinedValuesObject });
}
  1. The omitBy function checks your filters object and removes any value that is null or undefined (if you take it out, the lodash.filter function wont return any result.

  2. The filter function will filter out all the objects who's values don't match with the object you pass as a second argument to the function (which in this case, is your filters object.)

Why use this?

Well, assume you have this object:

const myFiltersObj = {

   name: "Java",
   age: 50

};

If you want to add another filter, just add a new property to the myFilterObj, like this:

const myFiltersObj = {

   name: "Java",
   email: 50,
   country: "HND"

};

Call the getUsersWithFilter function, and it will work just fine. If you skip, let's say the name property in the object, the getUsersWithFilter function will filter by the email and country just fine.

LuisDev99
  • 1,697
  • 17
  • 13
0

Please check below code snippet with data you provided, it will return filtered data on the basis of multiple columns.

var filter = {
  address: 'India',
  age: '27'
};

var users = [{
    name: 'Nikhil',
    email: 'nikhil@mail.com',
    age: 27,
    address: 'India'
  },
  {
    name: 'Minal',
    email: 'minal@mail.com',
    age: 27,
    address: 'India'
  },
  {
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    address: 'USA'
  },
  {
    name: 'Tom',
    email: 'tom@mail.com',
    age: 35,
    address: 'England'
  },
  {
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    address: 'England'
  }
];


function filterByMultipleColumns(users, columnDataToFilter) {
  return users.filter(row => {
    return Object.keys(columnDataToFilter).every(propertyName => row[propertyName].toString().toLowerCase().indexOf(columnDataToFilter[propertyName].toString().toLowerCase()) > -1);
  })
}

var filteredData = filterByMultipleColumns(users, filter);

console.log(filteredData);

Result : [ { "name": "Nikhil", "email": "nikhil@mail.com", "age": 27, "address": "India" }, { "name": "Minal", "email": "minal@mail.com", "age": 27, "address": "India" } ]

Please check below link which can used with just small changes Javascript filter array multiple values – example

Nikhilus
  • 9
  • 1
0

Here is the basic function for this:

const getValue = (value) =>
    typeof value === "string" ? value.toUpperCase() : value;


function filterPlainArray(array, filters) {
    const filterKeys = Object.keys(filters);
    return array.filter((item) => {
        return filterKeys.every((key) => {
            if (!filters[key].length) {
                return true;
            }
            return filters[key].find(
                (filter) => getValue(filter) === getValue(item[key])
            );
        });
    });
}

let filters = {
    color: ["yellow"],  OR  ["yellow", "orange"] // if you want many options
    rentedOut: [true],
};


let a = filterPlainArray(data, filters);
console.log(a);
console.log(a.length);

if you need RANGE e.g. prices, then you need to add this function:

function range(start, end) {
    start = parseFloat(start);
    end = parseFloat(end);
    return new Float32Array(end - start).fill().map((d, i) => i + start);
}

now your filters should look like this:

let filters = {
    color: [],
    rentedOut: [],
    miles: range(50000, 125000),
};

Sources:

fruitloaf
  • 1,628
  • 15
  • 10
0

Vue3 Pinia

I put the answer of trincot in Vue 3 Pinia context:

state: () => ({

    data: [{...}, {...}, ...],

    filter: {address: ['England', 'Scotland'], name: ['Mark'] }

}),

getters: {

    list: (state) => {

        return state.data.filter(obj =>
            Object.entries(state.filter).every(([prop, find]) => find.includes(obj[prop]))
        );
    },
}
Faris Han
  • 525
  • 3
  • 16
-1
const data = [{
    realName: 'Sean Bean',
    characterName: 'Eddard “Ned” Stark'
}, {
    realName: 'Kit Harington',
    characterName: 'Jon Snow'
}, {
    realName: 'Peter Dinklage',
    characterName: 'Tyrion Lannister'
}, {
    realName: 'Lena Headey',
    characterName: 'Cersei Lannister'
}, {
    realName: 'Michelle Fairley',
    characterName: 'Catelyn Stark'
}, {
    realName: 'Nikolaj Coster-Waldau',
    characterName: 'Jaime Lannister'
}, {
    realName: 'Maisie Williams',
    characterName: 'Arya Stark'
}];

const filterKeys = ['realName', 'characterName'];


const multiFilter = (data = [], filterKeys = [], value = '') => data.filter((item) => filterKeys.some(key => item[key].toString().toLowerCase().includes(value.toLowerCase()) && item[key]));


let filteredData = multiFilter(data, filterKeys, 'stark');

console.info(filteredData);
/* [{
  "realName": "Sean Bean",
  "characterName": "Eddard “Ned” Stark"
}, {
  "realName": "Michelle Fairley",
  "characterName": "Catelyn Stark"
}, {
  "realName": "Maisie Williams",
  "characterName": "Arya Stark"
}]
 */
Hamo
  • 1
  • 1
-1
arr.filter((item) => {
       if(condition)
       {
         return false;
       }
       return true;
    });
Mohak Londhe
  • 372
  • 2
  • 9
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value – B001ᛦ May 18 '21 at 19:13
  • Checks multiple conditions and return true or false in JS filter – Mohak Londhe Jun 01 '21 at 12:23