0

A am trying to return a new array that is filtered on sub-properties of objects.

I am trying to nest two filters together to achieve this result.

let header = "xyz";

let data = [{
  "header": header,
  items: [{
    id: 1,
    status: "Y"
  }, {
    id: 2,
    status: "N"
  }, {
    id: 3,
    status: "N"
  }]
},{
  "header": header,
  items: [{
    id: 1,
    status: "N"
  }, {
    id: 2,
    status: "Y"
  }]
}];

let result = data.filter(item => {
  return item.items.filter(item => {
    return item.status === "Y";
  })
});

Expected output

[{
  "header": header,
  items: [{
    id: 1,
    status: "Y"
  }]
},{
  "header": header,
  items: [{
    id: 2,
    status: "Y"
  }]
}];

How can I filter the original array where status === 'Y'?

2
  • Yeah, your inner filter returns an empty array which is evaluated to true, so nothing gets filtered. Add .length to the inner filter or use .some. Commented Jun 24, 2019 at 18:11
  • .some returns { id: 1, status: 'Y' }, { id: 1, status: 'N' }, { id: 2, status: 'Y' } Commented Jun 24, 2019 at 18:17

2 Answers 2

2

You could map first to get an equivalent array with filtered sub-items, then filter the main array to remove the elements with no sub-items.

let result = data.map(item => {
    return {
        header: item.header,
        items: item.items.filter(subItem => subItem.status === 'Y')
    };
}).filter(item => item.items.length);
Sign up to request clarification or add additional context in comments.

Comments

1

To achieve expected result, use below option of using reduce

  1. Loop data using reduce
  2. Update each object.items before pushing to accumulator-acc of reduce

working code

let header = "xyz";

let data = [{
  "header": header,
  items: [{
    id: 1,
    status: "Y"
  }, {
    id: 2,
    status: "N"
  }, {
    id: 3,
    status: "N"
  }]
},{
  "header": header,
  items: [{
    id: 1,
    status: "N"
  }, {
    id: 2,
    status: "Y"
  }]
}];

console.log(data.reduce((acc,v) => {
  v. items = v.items.filter(item => {
    return item.status === "Y";
  })
  acc.push(v)
   return acc
}, []))

codepen - https://codepen.io/nagasai/pen/EBXvLx

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.