Home > Software design >  How to filter an array with a special condition
How to filter an array with a special condition

Time:11-11

I'm trying to filter some data but I am trying to get all the elements with the same id that have the number 3.

The id 10 and 300 has number 3 so I want to get all the elements with id 10 and 300

Is it possible to do this using filters? My current code is filtering too much elements

const data = [{
    id: 10,
    number: 3
  }, {
    id: 10,
    number: 2
  }, {
    id: 300,
    number: 1
  }, {
    id: 300,
    number: 3
  }, {
    id: 40,
    number: 1
  },
  {
    id: 40,
    number: 2
  }
]

const filteredData = data.filter(elem => elem.number === 3);
console.log(filteredData);

Expected Result:

{
      id: 10,
      number: 3
    }, {
      id: 10,
      number: 2
    }, {
      id: 300,
      number: 1
    }, {
      id: 300,
      number: 3
    }

CodePudding user response:

First create a Set which contains all the id you want. Then filter the list again based on the id.

const data = [{
    id: 10,
    number: 3
  }, {
    id: 10,
    number: 2
  }, {
    id: 300,
    number: 1
  }, {
    id: 300,
    number: 3
  }, {
    id: 40,
    number: 1
  },
  {
    id: 40,
    number: 2
  }
]

const ids = new Set(data.filter(d => d.number === 3).map(d => d.id));

const filteredData = data.filter(d => ids.has(d.id));

console.log(filteredData);

CodePudding user response:

Using some() can also do it

data.filter(d => data.filter(d => d.number == 3).map(d => d.id).some(i => i == d.id))

const data = [{
    id: 10,
    number: 3
  }, {
    id: 10,
    number: 2
  }, {
    id: 300,
    number: 1
  }, {
    id: 300,
    number: 3
  }, {
    id: 40,
    number: 1
  },
  {
    id: 40,
    number: 2
  }
]

let result = data.filter(d => data.filter(d => d.number == 3).map(d => d.id).some(i => i == d.id))
console.log(result)

  • Related