Reputation: 47
I have a planning, with multiple items. My object is like this :
planning: [
{ id: '1', equipe: [ '1', '2' ] },
{ id: '2', equipe: [ '1' ] },
{ id: '3', equipe: [ '2', '3' ] }
...
]
I want to filter this array to hide or show planning items. My shown array is :
checked: [ '1', '4' ]
So, the array planning could be filtered by equipe array, so it should be :
planning: [
{ id: '1', equipe: [ '1', '2' ] },
{ id: '2', equipe: [ '1' ] }
]
I've tried to filter array but I don't see how indexOf could work with array and not string. I've also tried includes function but this doens't work:
planning.filter(item => checked.includes(item.equipe))
Thask for help !
Upvotes: 0
Views: 38
Reputation: 512
I would implement the logic in this manner.
//Original Data
let planning = [
{ id: '1', equipe: ['1', '2'] },
{ id: '2', equipe: ['1'] },
{ id: '3', equipe: ['2', '3'] }
]
/**
* Converting checked into Set so it will maintain all the unique values.
* I can check which elements are present in O(1) using checked.has(value)
*/
let checked = new Set(['1', '4'])
/**
* Using standard filter() function.
* Using some() to check if atleast 1 element from equipe is present in Set.
* If yes then checked.has(element) evaluates to true and some() receives atleast 1 element is valid and the element passes the filter.
*/
let filtered = planning.filter(plan => {
return plan.equipe.some(element => checked.has(element));
})
console.log(filtered)
Upvotes: 0
Reputation: 10382
you need iterate over each value from item.equipe
against checked
, you could use some to check if at least one matches checked
array:
planning.filter(item => item.equipe.some(val => checked.includes(val)))
const planning = [
{ id: '1', equipe: [ '1', '2' ] },
{ id: '2', equipe: [ '1' ] },
{ id: '3', equipe: [ '2', '3'] }
]
const checked = [ '1', '4' ]
const filtered = planning.filter(item => item.equipe.some(val => checked.includes(val)))
console.log(filtered)
Upvotes: 1