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
To filter
arrayA
based on the filters infilteredArrayOrderlyOn
in the correct order, you can iterate over the filters and apply them sequentially to the array.In this
filteredArrayOrderlyOn
is iterated over, and for each filter, thefilteredArray
is further filtered based on the key-value pair in the filter object. This ensures that the filters are applied in the correct order.You can use
Array#every()
to match any number of keys in the filters: