Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I filter the data where the colors is less than 20?

I have this sample data and I wanted to filter it where the colors are less than 20 or equal to 20:

const data = [
  {
    colors: { green: 8 },
    name: "Item1"
  },
  {
    colors: { Black: 6, Green: 7 },
    name: "Item2"
  },
  {
    colors: { Green: 20, Yellow: 31, Pink: 36 },
    name: "Item2"
  },
  {
    colors: { Black: 39, Red: 21 },
    name: "Item4"
  }
];

I recreated this in codesandbox: https://codesandbox.io/s/magical-margulis-yy1moz?file=/src/App.js

I tried this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const data = [{colors: { green: 8 },name: "Item1"},{colors: { Black: 6, Green: 7 },name: "Item2"},{colors: { Green: 20, Yellow: 31, Pink: 36 },name: "Item2"},{colors: { Black: 39, Red: 21 },name: "Item4"}];

const newData = data.filter((item) => {
  return Object.entries(item.colors).filter((c) => c[1] < 20);
});

console.log(newData);

It does not correctly filter. I can still see all of the items even if they are more than 20

The expected output would be to show the filtered data:

Item1, green: 8
Item2, Black: 6, Green: 7,
Item3, Green: 20 

>Solution :

You can filter on color value using array#filter and create a new colors object and push it in result using array#reduce.

const data = [ { colors: { green: 8 }, name: "Item1" }, { colors: { Black: 6, Green: 7 }, name: "Item2" }, { colors: { Green: 20, Yellow: 31, Pink: 36 }, name: "Item2" }, { colors: { Black: 39, Red: 21 }, name: "Item4" } ],
      result = data.reduce((r, o) => {
        const colors = Object.entries(o.colors).filter(([,val]) => val <= 20);
        if(colors.length) {
          r.push({ colors: Object.fromEntries(colors), name: o.name });
        }
        return r;
      },[]);
console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading