Mandoxsy
Mandoxsy

Reputation: 103

filtering an array of objects based on another array returning new array javascript

I have an array of object, which we can call arrayOne and want to check with arrayTwo if it contain any string that match with ArrayOne, and it will return new array with matching array. What is the best approach I can do using ES6 ?

Example :

ArrayOne =    [  
       {  
          "sessionId":1,
          "name":"session name 1",
          "types":[  
             "type1",
             "type 2"
          ],
          "tracks":[  
             "track1",
             "track 2"
          ]
       },
       {  
          "sessionId":2,
          "name":"session name 2",
          "types":[  
             "track 3",
             "type 2"
          ],
          "tracks":[  
             "track 3",
             "track 2"
          ]
       }
    ]


arrayTwo = ["track 3"] // or it can be ["track&3", "Type 2"] which it will return both array

return

newArray =  [ {  
      "sessionId":2,
      "name":"session name 2",
      "types":[  
         "track 3",
         "type 2"
      ],
      "tracks":[  
         "track 3",
         "track 2"
      ]
   }]

I tried the following :

arrayOne.filter((obj) => {
                Object.keys(obj).forEach((key) => {
                    if (obj[key].toString().indexOf(arrayTwo) !== -1) {
                        this.setState({
                            newArray: [obj]
                        })
                    }
                });
            });

Upvotes: 1

Views: 52

Answers (1)

Erik
Erik

Reputation: 99

If you only care about the tracks array, you could do something like this:

ArrayOne.filter((obj) => arrayTwo.some(x => obj.tracks.includes(x)));

.some() returns true if arrayTwo contains some element x such that obj.tracks has a matching element.

Upvotes: 1

Related Questions