I have an array object called fullvalue. I also have a string in an array called pushedimg.
I used the filter function here to write the code so that if there is a value that does not match between the value of fullvalue.name and the string of pushedimg, it is put in a variable called filters.
This is what I intended answer.
const fullvalue = [
{diaryItemId: 138, name: "growthLength", value: "1"}
{diaryItemId: 141, name: "wormHeadSize", value: "2"}
]
const pushedimg = ["growthLength"]
const filters = fullvalue.filter((v) => !v.name.includes(pushedimg))
answer
filters = [{diaryItemId: 141, name: "wormHeadSize", value: "2"}]
However, if the value of pushedimg has one more value of wormHeadSize, the values of fullvalue.name and pushedimg both match, so there should be only an empty array in the filters variable, but two values are entered.
like this code
const fullvalue = [
{diaryItemId: 138, name: "growthLength", value: "1"}
{diaryItemId: 141, name: "wormHeadSize", value: "2"}
]
const pushedimg = ["growthLength", "wormHeadSize"]
const filters = fullvalue.filter((v) => !v.name.includes(pushedimg))
answer
filters = [
{diaryItemId: 138, name: "growthLength", value: "1"}
{diaryItemId: 141, name: "wormHeadSize", value: "2"}
]
expected answer
filters = []
How can i fix my code?
CodePudding user response:
If you only want to filter out exact matches you can simply do
fullvalue.filter((v) => !pushedimg.includes(v.name))
but if you want to do a partial match on the name you need to iterate over the items in pushedimg
and check each value against v.name
, then if any match is found use that for the filtering. You can do that like this:
fullvalue.filter((v) => !pushedimg.some((pi) => v.name.includes(pi)))