I have printed arr values in console they are like
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
but when this function gives an error i am not getting any values in arr
Uncaught Type Error: arr.filter is not a function
I am new to java-script and i don't have any idea what's this error is
function filter(arr, criteria) {
return arr.filter(function (obj) {
return Object.keys(criteria).every(function (c) {
return obj[c] == criteria[c];
});
});
}
I have printed arr values in console they are like
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
but when this function gives an error i am not getting any values in arr
Uncaught Type Error: arr.filter is not a function
I am new to java-script and i don't have any idea what's this error is
function filter(arr, criteria) {
return arr.filter(function (obj) {
return Object.keys(criteria).every(function (c) {
return obj[c] == criteria[c];
});
});
}
Share
Improve this question
edited Nov 20, 2019 at 9:20
NullDev
7,3194 gold badges35 silver badges58 bronze badges
asked Nov 20, 2019 at 7:50
Ankit YadavAnkit Yadav
271 gold badge1 silver badge6 bronze badges
4
-
is
**arr**
actually in your code or did you just try to highlight it? – NullDev Commented Nov 20, 2019 at 8:00 - @NullDev yes i highlight it – Ankit Yadav Commented Nov 20, 2019 at 8:35
-
The error states that the
.filter()
function doesn't apply to the type that is stored inarr
.var x = [];x.filter(function() {})
confirms that.filter
works on an array. Therefore yourarr
variable is not an array. – fdomn-m Commented Nov 20, 2019 at 8:40 -
Regardless of what you get in console, how do you generate
arr
that you pass into your filter function? – fdomn-m Commented Nov 20, 2019 at 8:40
1 Answer
Reset to default 2Seems like the arr you are sending to the filter function is not an array, which is why the error is saying that arr.filter is not a function.
Just tried this and it works, so your function seems ok:
function filter(arr, criteria) {
return arr.filter(function (obj) {
return Object.keys(criteria).every(function (c) {
return obj[c] == criteria[c];
});
});
}
const arr = [
{
name: "David",
age: 54
},
{
name: "Andrew",
age: 32
},
{
name: "Mike",
age: 54
}
];
const myFilter = {"age": 54};
const result = filter(arr, myFilter);
console.log(result);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745619786a4636450.html
评论列表(0条)