close

How to filter array when object key value is in array

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to filter array when object key value is in array in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to filter array when object key value is in array ?

  1. How to filter array when object key value is in array ?

    to filter array when object key value is in array In case you have key value pairs in your input array, I used:
    .filter( this.multi_items[0] != null && store.state.isSearchBox === false ? item => _.map(this.multi_items, "value").includes(item["wijknaam"]) : item => item["wijknaam"].includes("") );

  2. How to filter array when object key value is in array ?

    to filter array when object key value is in array In case you have key value pairs in your input array, I used:
    .filter( this.multi_items[0] != null && store.state.isSearchBox === false ? item => _.map(this.multi_items, "value").includes(item["wijknaam"]) : item => item["wijknaam"].includes("") );

Method 1

You can do it with Array.prototype.filter(),

var data = { records : [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }] }
var empIds = [1,4,5]
var filteredArray = data.records.filter(function(itm){
  return empIds.indexOf(itm.empid) > -1;
});

filteredArray = { records : filteredArray };

If​ the ​callBack​ returns a ​true​ value, then the ​itm​ passed to that particular callBack will be filtered out. 

Method 2

In case you have key value pairs in your input array, I used:

.filter(
          this.multi_items[0] != null && store.state.isSearchBox === false
            ? item =>
                _.map(this.multi_items, "value").includes(item["wijknaam"])
            : item => item["wijknaam"].includes("")
        );

where the input array is multi_items as: [{“text”: “bla1”, “value”: “green”}, {“text”: etc. etc.}]

_.map is a lodash function.

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment