1

I'm trying to filter objects in an array that contain specific values inside a property that is an array. Example, here is my array of objects:

[
  {_id: 1, value: ['Row', 'Column']}, 
  {_id: 2, value: []}, 
  {_id: 3, value: ['Row']}, 
  {_id: 4},
  {_id: 5, value: ['Column']}
]

I need it to return all objects with 'Row' in the value array, i.e. the result should be:

[
  {_id: 1, value: ['Row', 'Column']}, 
  {_id: 3, value: ['Row']},
]

Here's my method to do this but it's returning null:

findRowValues() {
    let groupObj = [
       {_id: 1, value: ['Row', 'Column']}, 
       {_id: 2, value: []}, 
       {_id: 3, value: ['Row']}, 
       {_id: 4},
       {_id: 5, value: ['Column']}
    ];
    
    return groupObj.filter(function (obj) {
          return (
            obj.value &&
            obj.value.find(o => { o === 'Row' })
          )
    });
}

2 Answers 2

1

That's due to the { } inside the callback of find. Those can be removed for implicit return or you need to use return keyword explicity. I have used implicit return due to arrow function.

let groupObj = [
          {_id: 1, value: ['Row', 'Column']}, 
          {_id: 3, value: []}, 
          {_id: 5, value: ['Row']}, 
          {_id: 7},
          {_id: 8, value: ['Column']}
    ];


function findRowValues(groupObj) {
    return groupObj.filter(function (obj) {
          return (
            obj.value &&
            obj.value.find(o => o === 'Row' )
          )
    });
}

console.log(findRowValues(groupObj))

For return key word - obj.value.find(o => {return o === 'Row'} )

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

Comments

0

Use destructuring and includes method

function findRowValues() {
  const groupObj = [
    { _id: 1, value: ["Row", "Column"] },
    { _id: 2, value: [] },
    { _id: 3, value: ["Row"] },
    { _id: 4 },
    { _id: 5, value: ["Column"] },
  ];

  return groupObj.filter(({ value = [] }) => value.includes("Row"));
}

console.log(findRowValues())

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.