0

I want to filter through an array and retrieve items if their filters match. However it does not work.

const wanted=["apple"]
const items = [
  {
    "name": "Iphone"
    "filters": ["phone","apple"]
  },
  {
    "name": "samsung12"
    "filters": ["samsung12","samsung"]
  },
]

let desiredList = items.filter((val) => wanted.includes(val.filters));

Any ideas on how i could get this to work?

3
  • You sure items is an array? Commented Jan 12, 2023 at 20:47
  • @technophyle edited it yes its an array with many objects but simplified it in demo Commented Jan 12, 2023 at 20:49
  • 1
    includes method doesn't work like that. See documentation again. Commented Jan 12, 2023 at 20:51

3 Answers 3

2

You would need to use some to check if any of the filters contains a value in wanted:

const wanted = ["apple"]
const items = [{
  "name": "Iphone",
  "filters": ["phone", "apple"]
}, {
  "name": "samsung12",
  "filters": ["samsung12", "samsung"]
}];

let desiredList = items.filter((item) => item.filters.some((f) => wanted.includes(f)));

console.log(desiredList);

Sign up to request clarification or add additional context in comments.

Comments

1
const wanted="apple"
const items = [
"name": "Iphone"
"filters": ["phone","apple"]
]

let desiredList = 
items.filter((val)=> 
val.filters.includes(wanted) )

3 Comments

wanted is supposed to be an array, though.
wanted is an array but thanks for help manage to solve
Thats the point, based on his code example I though that the problem is declaring wanted as an array !
1

simply you need to filter your items searching the required field, then map the result using .map for each result

here you can check it

let abc = document.querySelectorAll('div')

const wanted=["apple"]
const items = [{
  "name": "Iphone",
  "filters": ["phone","apple"]
},{
  "name": "Iphone",
  "filters": ["phone","sony"]
},{
  "name": "Iphone",
  "filters": ["phone","samsung"]
}]

items.filter((val) => val["filters"].includes(wanted[0])).map((item) => { item? abc[0].innerHTML += item.name+"<br />"+item.filters : console.log("none") })
<div></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.