1

I've got an array like this:

const rawdata = [
  {
    top_feature_col: "s9",
    top_feature_row: 1,
    data: [{ cluster: 0, value: 151508, opportunity_perc: 69 }]
  },
  {
    top_feature_col: "s9",
    top_feature_row: 2,
    data: [{ cluster: 0, value: 127518, opportunity_perc: 70 }]
  },
  {
    top_feature_col: "s9",
    top_feature_row: 2,
    data: [{ cluster: 1, value: 12668, opportunity_perc: 40 }]
  }
];

I'd like to filter where opportunity_perc >= 50 but I don't know how to do it.

The result should be:

const result = [
  {
    top_feature_col: "s9",
    top_feature_row: 1,
    data: [{ cluster: 0, value: 151508, opportunity_perc: 69 }]
  },
  {
    top_feature_col: "s9",
    top_feature_row: 2,
    data: [{ cluster: 0, value: 127518, opportunity_perc: 70 }]
  }
];
Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
SkuPak
  • 307
  • 8
  • 16
  • What will happen if any object in `data` array have `opportunity_perc` less than 50? – brk May 12 '20 at 16:04
  • 1
    Does this answer your question? [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) – PeterKA May 12 '20 at 16:15

3 Answers3

7

You should try with the filter method of Array class:

const result = rawdata
    .filter(({data}) => data[0].opportunity_perc >= 50);

That will be valid if the data array will contains only one element (as per your example) if it's not you should specify in your request here what should be the behaviour.

Raffaele
  • 737
  • 7
  • 21
1

const rawdata = [
    {
        top_feature_col: "s9",
        top_feature_row: 1,
        data: [{cluster: 0, value: 151508, opportunity_perc: 69}]
    },
    {
        top_feature_col: "s9",
        top_feature_row: 2,
        data: [{cluster: 0, value: 127518, opportunity_perc: 70}]
    },
    {
        top_feature_col: "s9",
        top_feature_row: 2,
        data: [{cluster: 1, value: 12668, opportunity_perc: 40}]
    }
];

let filteredData = rawdata.filter((item) => {
    return ((item.data[0].opportunity_perc) >= 50);
});

console.log(filteredData);
1

use the filter method with destructure and have the check with opportunity_perc

const rawdata = [
  {
    top_feature_col: "s9",
    top_feature_row: 1,
    data: [{ cluster: 0, value: 151508, opportunity_perc: 69 }]
  },
  {
    top_feature_col: "s9",
    top_feature_row: 2,
    data: [{ cluster: 0, value: 127518, opportunity_perc: 70 }]
  },
  {
    top_feature_col: "s9",
    top_feature_row: 2,
    data: [{ cluster: 1, value: 12668, opportunity_perc: 40 }]
  }
];

const res = rawdata.filter(
  ({ data: [{ opportunity_perc }] }) => opportunity_perc >= 50
);

console.log(res);
Siva K V
  • 10,561
  • 2
  • 16
  • 29