skip to Main Content

here is my data:

arrayA= [{"studentID":1,"Type":"A"},{"studentID":2,"Type":"B"},{"studentID":3,"Type":"C"},{"studentID":4,"Type":"A"}]
filteredArrayOrderlyOn = [{"studentID":1},{"Type":"A"}] (depending on the order the user selects the filters)

Output should be 
arrayA = [{"studentID":1,"Type":"A"}]

or if the filteredArrayOrderlyOn array changes because user has control on this selection.

filteredArrayOrderlyOn  = [{"Type":"B"},{"studentID":1}] then output should be nothing []
Or if  
fillteredArrayOrderlyOn  = [{"Type":"A"}] 
then output should be
arrayA= [{"studentID":1,"Type":"A"},{"studentID":4,"Type":"A"}]

So i would like to filter ArrayA, in the correct order, meaning that in filteredArrayOrderly first the filter should be studentID=1 and then Type which is A.

i have been trying without any luck


newArray = arrayA.filter(function (item) {
    return Object.keys(elem) === Object.keys(item);
  });
})

or using lodash

 newArray = _.filter(arrayA, function (elem) {
  //     return elem.Type=== filteredArrayOrderlyOn.Type ||  elem.studentID=== filteredArrayOrderlyOn.studentID
  //   });

but getting too many repetitions
thakns guys

2

Answers


  1. To filter arrayA based on the filters in filteredArrayOrderlyOn in the correct order, you can iterate over the filters and apply them sequentially to the array.

    let arrayA = [
      { "studentID": 1, "Type": "A" },
      { "studentID": 2, "Type": "B" },
      { "studentID": 3, "Type": "C" },
      { "studentID": 4, "Type": "A" }
    ];
    
    let filteredArrayOrderlyOn = [
      { "studentID": 1 },
      { "Type": "A" }
    ];
    
    let filteredArray = arrayA;
    
    filteredArrayOrderlyOn.forEach(filter => {
      const key = Object.keys(filter)[0];
      const value = filter[key];
      filteredArray = filteredArray.filter(item => item[key] === value);
    });
    
    console.log(filteredArray);
    
    

    In this filteredArrayOrderlyOn is iterated over, and for each filter, the filteredArray is further filtered based on the key-value pair in the filter object. This ensures that the filters are applied in the correct order.

    Login or Signup to reply.
  2. You can use Array#every() to match any number of keys in the filters:

    let arrayA = [
      { "studentID": 1, "Type": "A" },
      { "studentID": 2, "Type": "B" },
      { "studentID": 3, "Type": "C" },
      { "studentID": 4, "Type": "A" }
    ];
    
    let filteredArrayOrderlyOn = [
      { "studentID": 1 },
      { "Type": "A" }
    ];
    
    const result = arrayA.filter(item => 
      filteredArrayOrderlyOn.every(filter => Object.keys(filter).every(key => item[key] === filter[key]))
    );
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search