How to Filter a JavaScript Array With Another Array

Robin
Updated on February 27, 2024

Filter a JavaScript Array with Another Array

You can use the filter() method along with some conditions to filter a JavaScript array based on the elements of the second array.

          const items = [
    { id: 1, name: 'Apple' },
    { id: 2, name: 'Banana' },
    { id: 3, name: 'Orange' },
    { id: 4, name: 'Mango' },
]

const idsToFilter = [2, 3]

const filteredItems = items.filter((item) => {
    return idsToFilter.includes(item.id)
})

console.log(filteredItems)

        

Output:

          [
    { id: 2, name: 'Banana' },
    { id: 3, name: 'Orange' }
]

        

I have an array of items that I want to filter using the idsToFilter array of IDs.

Call the filter() method on the items array. It will loop through each item of this array, and inside the callback function, you can access each item.

Call the includes() method on the idsToFilter array to check if item.id is present in idsToFilter array.

If idsToFilter includes the item.id, the function returns true, and that item will be included in the filteredItems array.


Filter a JavaScript Array with an Array of Objects

If you want to filter an array in JavaScript against an array of objects, you can't use the includes() with the filter() method.

Because the includes() method only works with an array of primitive values.

You have to use the some() with the filter() method to filter a JavaScript array with an array of objects.

          const items = [
    { id: 1, name: 'Apple' },
    { id: 2, name: 'Banana' },
    { id: 3, name: 'Orange' },
    { id: 4, name: 'Mango' },
]

const filters = [
    { id: 2, name: 'Banana' },
    { id: 3, name: 'Orange' },
]

const filteredItems = items.filter((item) => {
    return filters.some((filter) => {
        return filter.id === item.id
    })
})

console.log(filteredItems)

        

Output:

          [
    { id: 2, name: 'Banana' },
    { id: 3, name: 'Orange' }
]

        

I want to filter the items array based on the filters array of objects. So I am calling the filter() method on the items array to loop through it and access each item.

I am calling the some() method and checking if the item.id matches with any object in the filters array.

If a matching object is found in filters array, the some() method returns true, and the filter() method includes the item in the filteredItems array.

You can adjust the condition inside some() method as needed based on your specific filtering criteria.

Related Posts