Home > Software engineering >  Refactoring request: Trying to find more optimal way to filter an array of objects applying several
Refactoring request: Trying to find more optimal way to filter an array of objects applying several

Time:03-24

Trying to filter an array of objects by the properties of another array of objects:

Data that I have

const filters = [
    {
        "id": "breed",
        "value": "bulldog"
    },
    {
        "id": "owner",
        "value": "Kevin"
    }
]

const dogs = [
    {
        "name": "Zephyr",
        "breed": "bulldog",
      "owner":"Kevin"
    },
    {
        "name": "Dude",
        "breed": "labradoodle",
      "owner":"Lance"
    },
        {
        "name": "Mark",
        "breed": "yorkie",
      "owner":"Rob"
    },
      {
        "name": "Cheddar",
        "breed": "bulldog",
      "owner":"Kevin"
    },
]

Output should be look like that:

[ { name: "Cheddar", breed: "bulldog", owner: "Kevin", }, { name: "Zephyr", breed: "bulldog", owner: "Kevin", }, ];

But instead I am getting just:

[
    {
        "name": "Zephyr",
        "breed": "bulldog",
        "owner": "Kevin"
    }
]

This is what I am doing:

dogs.reduce((acc, obj) => {
  filters.forEach((element) => {
    if (dogs.find((i) => i[element.id].includes(element.value))) {
      if (!acc.some((e) => e[element.id].includes(element.value))) {
        acc.push({ ...obj });
      }
    }
  });
  return acc;
}, []);

CodePudding user response:

Using Array#filter and Array#every, get the list of dogs meeting the filters

const 
  filters = [ { "id": "breed", "value": "bulldog" }, { "id": "owner", "value": "Kevin" } ],
  dogs = [ { "name": "Zephyr", "breed": "bulldog", "owner":"Kevin" }, { "name": "Dude", "breed": "labradoodle", "owner":"Lance" }, { "name": "Mark", "breed": "yorkie", "owner":"Rob" }, { "name": "Cheddar", "breed": "bulldog", "owner":"Kevin" } ];
  
const filteredDogs = dogs.filter(dog => 
  filters.every(({ id, value }) => dog[id] === value)
);

console.log(filteredDogs);

CodePudding user response:

Here is your ans:

const result = dogs.filter(dog => {
  return filters.every(filter => dog[filter.id] == filter.value)
})

Code snippet

const filters = [
    {
        "id": "breed",
        "value": "bulldog"
    },
    {
        "id": "owner",
        "value": "Kevin"
    }
]

const dogs = [
    {
        "name": "Zephyr",
        "breed": "bulldog",
      "owner":"Kevin"
    },
    {
        "name": "Dude",
        "breed": "labradoodle",
      "owner":"Lance"
    },
        {
        "name": "Mark",
        "breed": "yorkie",
      "owner":"Rob"
    },
      {
        "name": "Cheddar",
        "breed": "bulldog",
      "owner":"Kevin"
    },
];

const result = dogs.filter((dog)=> {
  return filters.every((filter)=> dog[filter.id] == filter.value)
})

console.log(result)

  • Related