1

I have a object array in which each object contain an id and a name and a separate array contains a set of ids. I want to filter first array based on the second array.


const data= [
    {
        id: 1,
        name: 'name1'
    },
    {
        id: 2,
        name: 'name2'
    },
    {
        id: 3,
        name: 'name3'
    },
    {
        id: 4,
        name: 'name4'
    }
];
const array = [1,3,4];

const expectedResult= [
    {
        id: 1,
        name: 'name1'
    },
    {
        id: 3,
        name: 'name3'
    },
    {
        id: 4,
        name: 'name4'
    }
];
1
  • Hi Trishan! Please try my solution below and let me know if it helps. If you find that it was helpful, please consider marking it as the solution. :) Commented Jun 14, 2019 at 7:19

1 Answer 1

1

Use .filter and .includes

    const data= [
            {
                id: 1,
                name: 'name1'
            },
            {
                id: 2,
                name: 'name2'
            },
            {
                id: 3,
                name: 'name3'
            },
            {
                id: 4,
                name: 'name4'
            }
        ];

    const array = [1, 3, 4] 
    
    const result = data.filter((item) => {

       //gives us items that passes a condition
       return array.includes(item.id)
     
    })
    
    console.log(result)

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

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.