【问题标题】:Why is an empty array returned on filter().includes()? [duplicate]Why is an empty array returned on filter().includes()? [duplicate]
【发布时间】:2022-12-01 22:49:11
【问题描述】:

I can't figure out why my filter/includes is returning an empty array.

I have an array that works as the filter I set.

For example, filterLevels and the array is [100,200] This console.logs out correctly to an array with these vals (integers). The levels array in the data set are also integers and I've double checked. I've console logged out my data set and everything looks good there too.

I'd expect back every overlapping item in both my filtering array and data set. So for the above example I expect the first 3 items from the data set (where there is any match of levels).

console output is an empty array? I must be missing something small?

const filterLevels = [100,200]
const learningMapsData = [{
    "name": "Enterprise Networking",
    "Technology": "Networking",
    "levels": [100, 200]
  },
  {
    "name": "Develop",
    "Technology": "Software",
    "levels": [100, 200, 300]
  },
  {
    "name": "Test it out",
    "Technology": "Testing",
    "levels": [200, 300]
  },
  {
    "name": "Rout it",
    "Technology": "Routing",
    "levels": [300, 400]
  }
]

const intersection = learningMapsData.filter(element => filterLevels.includes(element.levels));
console.log("intersection::::::::::::", intersection);

【问题讨论】:

  • Please revise the demo above so it shows your problem.
  • element.levels is an array. You are checking if any of the elements in [100,200] is equal to an array. Both are numbers so they wont ever be equal to an array. (Though even if the elements in filterLevels were arrays, then they would still not be equal.)

标签: javascript arrays filter


【解决方案1】:

You may go like this:

const intersection = learningMapsData.filter(element => element.levels.find(level => filterLevels.includes(level)));

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 2022-12-01
    • 2019-03-11
    • 2022-11-09
    • 2020-08-25
    • 2022-12-19
    • 1970-01-01
    • 2020-11-23
    • 2022-12-02
    相关资源
    最近更新 更多