1

I'm trying to find is_Y === 'Y' object from like this code

const tmpArray = [
    [{ "no": 1, "is_Y": "Y", }],
    [{ "no": 2, "is_Y": "N", }],
    [{ "no": 3, "is_Y": "Y", }],
    [{ "no": 3, "is_Y": "N", }],
    [{ "no": 4, "is_Y": "Y", }],
    [{ "no": 5, "is_Y": "N", }, { "no": 6, "is_Y": "Y", }]
];

function findY(array) {
    return array.filter(function (item) {
        return item.filter(function (item2) {
           return item2.is_Y === 'Y';
         });
    });
}

console.log(findY(tmpArray));

result is

[
  [ { no: 1, is_Y: 'Y' } ],
  [ { no: 2, is_Y: 'N' } ],
  [ { no: 3, is_Y: 'Y' } ],
  [ { no: 3, is_Y: 'N' } ],
  [ { no: 4, is_Y: 'Y' } ],
  [ { no: 5, is_Y: 'N' }, { no: 6, is_Y: 'Y' } ]
]

but I'd like to get results format like below

[
  { no: 1, is_Y: 'Y' },
  { no: 3, is_Y: 'Y' },
  { no: 4, is_Y: 'Y' },
  { no: 6, is_Y: 'Y' } 
]

what shall I do?

2 Answers 2

2

The easiest fix is to add an flat() before calling filter():

const tmpArray = [
    [{ "no": 1, "is_Y": "Y", }],
    [{ "no": 2, "is_Y": "N", }],
    [{ "no": 3, "is_Y": "Y", }],
    [{ "no": 3, "is_Y": "N", }],
    [{ "no": 4, "is_Y": "Y", }],
    [{ "no": 5, "is_Y": "N", }, { "no": 6, "is_Y": "Y", }]
];

function findY(array) {
    return array.flat().filter(item2 => item2.is_Y === 'Y')
}

console.log(findY(tmpArray));

Output:

[
  {
    "no": 1,
    "is_Y": "Y"
  },
  {
    "no": 3,
    "is_Y": "Y"
  },
  {
    "no": 4,
    "is_Y": "Y"
  },
  {
    "no": 6,
    "is_Y": "Y"
  }
]
Sign up to request clarification or add additional context in comments.

3 Comments

No need to perform array.flatMap(e => e), you just need to flat the array with array.flat()
Ah your right, went to fast! THanks for the tip ;)
Thats my answer now :p Any how those were almost simultaneous posts
1

Just flat the array before you filter.

const tmpArray = [
  [{ no: 1, is_Y: "Y" }],
  [{ no: 2, is_Y: "N" }],
  [{ no: 3, is_Y: "Y" }],
  [{ no: 3, is_Y: "N" }],
  [{ no: 4, is_Y: "Y" }],
  [
    { no: 5, is_Y: "N" },
    { no: 6, is_Y: "Y" },
  ],
];

function findY(array) {
  return array.flat().filter((item) => item.is_Y === "Y");
}

console.log(findY(tmpArray));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.