1
let array1= [
    { "id": 100, name: "A", "details": [{"year": "2012"},{"data": "Test1"}]},
    { "id": 101, name: "B", "details": [{"year": "2013"},{"data": "Test2"}]},
    { "id": 102, name: "C", "details": [{"year": "2014"},{"data": "Test3"}]}
];

const array2= ['2012'];

Result I wanted

{ "id": 100, name: "A", "details": [{"year": "2012"}]}

I know i can filter the array with this code

array1.filter(o => 
  o.details.some(p=> {
    return array2.includes(p.year)
  })
)

But is there a way to remove the objects as well.

1
  • Simply assign the result of the .filter into the variable array1. Commented Jan 28, 2022 at 13:16

1 Answer 1

1

We can reduce to avoid multiple steps

This reduce filters and deletes part of the details array

let array1 = [
    { "id": 100, name: "A", "details": [{"year": "2012"},{"data": "Test1"}]},
    { "id": 101, name: "B", "details": [{"year": "2013"},{"data": "Test2"}]},
    { "id": 102, name: "C", "details": [{"year": "2014"},{"data": "Test3"}]}
];

const array2 = ['2012'];

let array3 = array1.reduce((acc, {id,name,details}) => {
  if (array2.includes(details[0].year)) {
    acc.push({ id, name, details: details[0] })
  }
  return acc
}, [])

console.log(array3)

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

2 Comments

Ok..is there a way to remove the other objects as well..like{ "data": "Test1" } when applying the filter.
See update using reduce

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.