Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array based on dynamic parameter

Say I have an array of json objects which looks like below:

var codes = [{
            "code_id": "1",
            "code_name": "code 1",            ,
             }, {
            "code_id": "2",
            "code_name": "code889",

             },
        // ... () ...    
             ]

How can I filter codes array based on dynamic input parameter?

So I am looking for a generic function which will take input array and key and value as i/p.

var filteredCodes = getFilteredCodes(codes, "code_id", 2);

Thanks.

like image 526
Navoneel Talukdar Avatar asked Dec 19 '16 16:12

Navoneel Talukdar


People also ask

How to use filter dynamic array function in Excel?

where array identifies the source data, include identifies the value(s) you want to see in the filtered data set, and the optional if_empty specifies the value to display when the result is an empty set. You can use FILTER() to return a single column or several.

How do you filter an array based on value?

To filter an array of objects based on a property:Use the Array. find() method to iterate over the array. On each iteration, check if the object's property points to the specific value. The find() method will return the first object that satisfies the condition.

How to filter in Excel array?

To filter a data in an array formula (to exclude or require certain values), you can use an array formula based on the IF, MATCH, and ISNUMBER functions. where "data" is the named range B4:D11 and "filter" is the named range F4:F6. Note: this is an array formula and must be entered with control + shift + enter.


2 Answers

Use Array.prototype.filter to filter out the result - see demo below:

var codes = [{"code_id": "1","code_name": "code 1"}, {"code_id": "2","code_name": "code889"}];

function getFilteredCodes(array, key, value) {
  return array.filter(function(e) {
    return e[key] == value;
  });
}

var filteredCodes = getFilteredCodes(codes, "code_id", 2);

console.log(filteredCodes);
like image 53
kukkuz Avatar answered Sep 28 '22 04:09

kukkuz


You could use Array#filter with the key and value.

function getFilteredCodes(array, key, value) {
    return array.filter(function (o) {
        return o[key] === value;
    });
}

var codes = [{ "code_id": "1", "code_name": "code 1", }, { "code_id": "2", "code_name": "code889" }],
    filteredCodes = getFilteredCodes(codes, "code_id", "2");

console.log(filteredCodes);
like image 40
Nina Scholz Avatar answered Sep 28 '22 04:09

Nina Scholz