(PROBLEM SOLVED! Check the solution in the responses)
Here's my query:
I am trying to filter an array of objects based on a specified object, but all my attempts have resulted in an empty array. I suspect that the issue lies in iterating over an array of objects rather than a simple array.
Below is the code snippet where I am facing this challenge:
I have included an example using UnderscoreJS for filtering
(Click on the button to view the outcome)
$(document).ready(function() {
/*
* BEGIN - Custom Filter using Underscore.js
*
*/
var arrObject = [{
"data": [{
"img": "test1"
},
{
"img": "test2"
},
{
"img": "/image_folder/sub_folder/886.jpg"
}
]
}];
var compare = [{
"img": "/image_folder/sub_folder/886.jpg"
}];
var finalArray;
$.each(arrObject, function(index, element) {
finalArray = _.filter(element.data, function(ev) {
return ev == compare;
});
});
console.log(finalArray);
/*
* END - Custom Filter using Underscore.js
*
*/
/*
* START - Original Filter from Underscore.js Documentation
*
*/
$(document).on("click", ".originalUnderscore", function() {
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) {
return num % 2 == 0;
});
console.log(evens);
});
/*
* END - Original Filter from Underscore.js Documentation
*
*/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<button class="originalUnderscore">Click to show the original filter</button>