Subset array of object based on keys from another array(not static) and then filter

I have an array of object which needs to be filtered based upon the certain value :

let data = 
[
  {
    "region": 28,
    "nuts": 33,
    "score" : 26
   }, 
  {
    "region": 18,
    "nuts": 22,
    "score" : 21
   }
]

The other array includes keys for which the above object is to be filtered and also subsetted :


// this changes everytime 
// it may include ALL the keys or only ONE key of above object 
let keysArray = ["region", "score"]
(OR )
let keysArray = ["region", "nuts"]

Now if the data needs to be filtered for region and score above 25 then it should return the following :

// when => keysArray = ["region", "score"]
// region && score >= 25 
// expected output
 [
  {
    "region": 28,
    "score" : 26
   }
 ]

// when => keysArray = ["region", "nuts"]
// region &&  nuts >= 25 
// expected output
 [
  {
    "region": 28,
    "nuts" : 33
   }
 ]

How can achieve this?
Thanks in advance.

PS : This does not answer the question –
filtering an array of objects based on another array in javascript

20 thoughts on “Subset array of object based on keys from another array(not static) and then filter”

  1. I created a working snippet.

    let data = [{
        region: 28,
        nuts: 33,
        score: 26
      },
      {
        region: 18,
        nuts: 22,
        score: 21
      }
    ];
    
    // this changes everytime
    // it may include ALL the keys or only ONE key of above object
    let keysArray = ["region", "score"];
    
    // Write Javascript code!
    const appDiv = document.getElementById("app");
    appDiv.innerHTML = `<h1>JS Starter</h1>`;
    
    const resultDiv = document.getElementById("result");
    
    filterData(keysArray, 25).forEach(item => {
      resultDiv.innerHTML += `<li>region: ${item.region}, score: ${
        item.score
      }</li>`;
    });
    
    function filterData(keys, val) {
      let result = [];
    
      data.forEach(dataItem => {
        let isEligible = false;
    
        for (let i = 0; i < keys.length; i++) {
          let key = keys[i];
          isEligible = dataItem[key] >= val;
          if (!isEligible) break;
        }
    
        if (isEligible) result.push(dataItem);
      });
    
      return result;
    }
    <div id="app"></div>
    
    <ul id="result"></ul>

    Working demo in stackblitz:
    https://stackblitz.com/edit/js-swutjy?embed=1&file=index.js

    Reply

Leave a Comment