2

I have an array of objects like below

const arr = 
  [ { a: '', b: '', arr: [ { label: '2' }, { label: '3' }                 ] } 
  , { a: '', b: '', arr: [ { label: '1' }, { label: '2' }, { label: '3' } ] } 
  , { a: '', b: '', arr: [ { label: '1' }, { label: '3' }                 ] } 
  ] 

I need to filter this array and get the objects in which the arr array has the label value of 2.

ie., expected result :

const arr = 
  [ { a: '', b: '', arr: [ { label: '2' }, { label: '3' }                 ] } 
  , { a: '', b: '', arr: [ { label: '1' }, { label: '2' }, { label: '3' } ] } 
  ] 

I have tried something like this:

array.forEach((item) => item.arr.filter(i) => i.label === '2')

how would we get back a filtered array looping through this array which has label values as "2" inside the arr array?

How can I achieve the expected result?

1
  • 1
    const result = arr.filter( ({ arr }) => arr.some( ({label}) => label === '2' )); Commented Aug 25, 2022 at 23:11

3 Answers 3

2

With filter, some and destructuring

const arr = 
  [ { a: '', b: '', arr: [ { label: '2' }, { label: '3' }                 ] } 
  , { a: '', b: '', arr: [ { label: '1' }, { label: '2' }, { label: '3' } ] } 
  , { a: '', b: '', arr: [ { label: '1' }, { label: '3' }                 ] } 
  ]
  
const output = arr.filter(({ arr }) => arr.some(({ label }) => label === '2'));
  
console.log(output)

Sign up to request clarification or add additional context in comments.

Comments

1

Like this:

let oldArray = array = [
   {
      "a":"",
      "b":"",
      "arr":[
         {
            "label":"2"
         },
         {
            "label":"3"
         }
      ]
   },
{
      "a":"",
      "b":"",
      "arr":[
         {
            "label":"1"
         },
         {
            "label":"2"
         },
         {
            "label":"3"
         }
      ]
   },
{
      "a":"",
      "b":"",
      "arr":[
         {
            "label":"1"
         },
         {
            "label":"3"
         }
      ]
   }
]

let newArray = oldArray.filter(item=>
  item.arr && item.arr.filter(inner=> inner.label == "2").length >= 1
)

console.log(newArray)

Comments

0

You can simply achieve this by using Array.filter() method along with Array.some()

Live Demo :

const arr = [
  { a: '', b: '', arr: [ { label: '2' }, { label: '3' }] },
  { a: '', b: '', arr: [ { label: '1' }, { label: '2' }, { label: '3' } ] },
  { a: '', b: '', arr: [ { label: '1' }, { label: '3' }] } 
];

const filteredArr = arr.filter(({ arr }) => arr.some(o => o.label === '2'));

console.log(filteredArr);

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.