简体   繁体   中英

Filter an array of objects based on another array

I want to filter this array of Object:

const testArray = [{
  id: 4,
  filters: ["Norway", "Sweden"]
}, {
  id: 2,
  filters :["Norway", "Sweden"]
}, {
  id: 3,
  filters:["Denmark", "Sweden"]
}]

with the filter

const myFilter=["Norway", "Sweden"]

However my code just returns []? What I have tried so far:

const testArray = [{
  id: 4,
  filters: ["Norway", "Sweden"]
}, {
  id: 2,
  filters :["Norway", "Sweden"]
}, {
  id: 3,
  filters:["Denmark", "Sweden"]
}]
const myFilter=["Norway", "Sweden"]

console.log(testArray.filter(e=>e.filters===myFilter))

You can use Array#every to test the equality + of two arrays as follows:

const output = testArray.filter(
    e => e.filters.every(
        filter => myFilter.includes(filter)
    )
);

 const testArray = [{ id: 4, filters: ["Norway", "Sweden"] }, { id: 2, filters:["Norway", "Sweden"] }, { id: 3, filters:["Denmark", "Sweden"] }], myFilter = ["Norway", "Sweden"], output = testArray.filter( e => e.filters.every( filter => myFilter.includes(filter) ) ); console.log(output)

NOTE : Array#every as used here just confirms that every element of each array is in the other, regardless of the order in which the elements appear .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM