How do I filter exact value in Javascript?

Viewed 70

I want where the color red and size 4gb just output the exact value but I am getting where size is 4 gb but color is green please help me in this regard. I am making a filter option, and my code is same so please if possible make it my code otherwise you can also suggest how can I achieve this?

const x = [
      {
      color: "green",
      name: "123",
      size: "4gb"
     },
    {
      color: "red",
      name: "555",
      size: "4gb"
    },
     {
      color: "green",
      name: "123",
      size: "2gb"
     },
     {
      color: "blue",
      name: "111",
      size: "2gb"
    },
    {
      color: "green",
      name: "123",
      size: "4gb"
    },
    {
      color: "red",
      name: "000",
      size: "4gb"
    }
  ]

const op = [{
  key: "color",
  item: "red"
},
{
  key: "size",
  item: "4gb"
}];

const fil = x.map(l => op.map(o => l[o.key] === o.item && l)).flat().filter(Boolean);

console.log(fil);

Output should be:

[{
  color: "red",
  name: "555",
  size: "4gb"
},{
  color: "red",
  name: "000",
  size: "4gb"
}];
1 Answers

You should filter() instead of map().

The primary operation you want to do is to filter() meaning the result contains less than or the same amount of values as the original array, so each item in the original array might or might not be present in the result so if you want a 1:1/0 mapping. A mapping always returns the same amount of values that are in the original array describing a 1:1 mapping, hence the name map().

Additionally use every() to loop over the filters. This will make sure all/ every (again, the name tells you what is does) filter condition is met.

const x = [
  {
    color: "green",
    name: "123",
    size: "4gb",
  },
  {
    color: "red",
    name: "555",
    size: "4gb",
  },
  {
    color: "green",
    name: "123",
    size: "2gb",
  },
  {
    color: "blue",
    name: "111",
    size: "2gb",
  },
  {
    color: "green",
    name: "123",
    size: "4gb",
  },
  {
    color: "red",
    name: "000",
    size: "4gb",
  },
];

const op = [
  {
    key: "color",
    item: "red",
  },
  {
    key: "size",
    item: "4gb",
  },
];

const fil = x.filter(option => op.every(({key, item}) => option[key] === item));
console.log(fil);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related