Sorry for the long title question didn't know how to properly formulate my question.
So this is the question, I got an array which stores objects, and within those objects there's another array with the key tags and which is an array that gets filled with tags.
Object:
var arr = new Array;
arr[0] = {
"like": 0,
"dislike": 0,
"answer": "body",
"tags" : ["offline", "facebook"],
"comments" : []
};
arr[1] = {
"like": 0,
"dislike": 0,
"answer": "body",
"tags" : ["school", "online"],
"comments" : []
};
arr[2] = {
"like": 0,
"dislike": 0,
"answer": "body",
"tags" : ["school", "offline"],
"comments" : []
};
The [0], [1] indexes respresent and ID, but that isn't really important here.
The problem is when I try to filter it with(I know it only tries to filter arr[0] atm but I will write a loop so it goes through all the indexes):
var toFind = "offline";
var filtered = arr[0].filter(function(el) {
return el.tags === toFind;
});
console.log(filtered);
It says arr[0].filter is not a function, but got no idea why it thinks arr[0] should be taken into account as a function.
When I remove the [0] it gives back a blank array...
So my question is how can I get the .filter function to give back the complete object based on tags in the tags array. So that if I search for the tag "school" it gives back arr[1] and arr[2], the complete objects.
Hope I my question is crystal clear and that I provided enough information. If you guys need anymore information, feel free to ask me for it. Or if you want me to clarify things, just ask :)
Hope you guys can help me!
Like has been said, arr[0] points to an object, which doesn't have a filter method. You need to call filter on the array itself
var tagToFind = "school";
var arr = new Array;
arr[0] = {
"like": 0,
"dislike": 0,
"answer": "body",
"tags" : ["offline", "facebook"],
"comments" : []
};
arr[1] = {
"like": 0,
"dislike": 0,
"answer": "body",
"tags" : ["school", "online"],
"comments" : []
};
arr[2] = {
"like": 0,
"dislike": 0,
"answer": "body",
"tags" : ["school", "offline"],
"comments" : []
};
var filtered = arr.filter(function(item){
return item.tags && //to account for undefined tags properties
item.tags.includes(tagToFind); //if you're supporting IE you will need to look and check each element instead
});
console.log(filtered);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments