0

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 !

3
  • 1
    planning.filter(item => checked.includes(item.equipe)) In this you are not checking if any element from checked array is present within the equipe instead you are checking whether checked contains the equipe array itself. Commented Mar 17, 2021 at 17:56
  • So what I have to do ? Commented Mar 17, 2021 at 18:06
  • Added my implementation below as an answer. Commented Mar 17, 2021 at 18:40

2 Answers 2

1

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)

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

Comments

0

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)

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.