-2

i have array like this

var listShow = [1, 3]

and this

[
{
  id: 1,
  name: 'JOHN',
},
{
  id: 2,
  name: 'JOHNE',
},
{
  id: 3,
  name: 'JOHNW',
}
]

And I only want to return array if id value is same as above array, I want result like this

[
    {
      id: 1,
      name: 'JOHN',
    },
    {
      id: 3,
      name: 'JOHNW',
    }
]

Does anyone know how to make the above possible? I've tried using array.filter but it doesn't work

  • 1
    You say `array.filter` doesn't work. Please can you explain how it doesn't work? Perhaps show us the code you've tried? – Matt Ellen Sep 08 '22 at 08:46
  • Please visit the [help], take the [tour] to see what and [ask]. Do some research - [search SO for answers](https://www.google.com/search?q=javascript+search+object+array+using+array+site%3Astackoverflow.com). If you get stuck, post a [mcve] of your attempt, noting input and expected output using the [\[<>\]](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Sep 08 '22 at 08:46
  • 1
    [dupe of dupes](https://stackoverflow.com/questions/68088158/how-to-filter-object-array-using-an-array-in-js) – mplungjan Sep 08 '22 at 08:48

1 Answers1

-1
var a = [
{
  id: 1,
  name: 'JOHN',
},
{
  id: 2,
  name: 'JOHNE',
},
{
  id: 3,
  name: 'JOHNW',
}
]
var b = a.filter((item) => listShow.includes(item.id) )

console.log(b)
Robert Rendell
  • 1,658
  • 15
  • 18