【问题标题】:Improve iteration through a long list of comparisons in an array.filter function通过 array.filter 函数中的一长串比较改进迭代
【发布时间】:2018-08-23 11:10:15
【问题描述】:

我不确定我的标题是否恰当地表达了我想要的。我基本上需要根据两个不同的属性从一个对象数组中过滤出一堆项目,这些属性需要与另一个数组相同,嗯......更像是它们需要与最后一个相同另一个数组的 6 项。

我目前正在手动执行此操作,这给了我这个丑陋的代码:

const filteredList = list.filter(x => {
  return (
    (x.someProperty === parseInt(anotherList[anotherList.length - 1][0].someProperty, 10) && x.anotherProperty === anotherList[anotherList.length - 1][0].anotherProperty) ||
    (x.someProperty === parseInt(anotherList[anotherList.length - 2][0].someProperty, 10) && x.anotherProperty === anotherList[anotherList.length - 2][0].anotherProperty) ||
    (x.someProperty === parseInt(anotherList[anotherList.length - 3][0].someProperty, 10) && x.anotherProperty === anotherList[anotherList.length - 3][0].anotherProperty) ||
    (x.someProperty === parseInt(anotherList[anotherList.length - 4][0].someProperty, 10) && x.anotherProperty === anotherList[anotherList.length - 4][0].anotherProperty) ||
    (x.someProperty === parseInt(anotherList[anotherList.length - 5][0].someProperty, 10) && x.anotherProperty === anotherList[anotherList.length - 5][0].anotherProperty) ||
    (x.someProperty === parseInt(anotherList[anotherList.length - 6][0].someProperty, 10) && x.anotherProperty === anotherList[anotherList.length - 6][0].anotherProperty)
  )
}

就目前而言,它目前正在工作,但必须有更好的方法来做到这一点,这正是我想知道的。那么有没有一种方法可以做到这一点,而不必为anotherList 的每个项目列出和进行比较?

谢谢

【问题讨论】:

  • anotherList有多长?
  • 情况不同。取决于之前的操作。
  • 一如既往,首先使用function 以避免所有代码重复!

标签: javascript arrays functional-programming javascript-objects


【解决方案1】:

您可以取出最后六项并检查给定的值。

const filteredList = list.filter(x =>
    anotherList
        .slice(-6)
        .some(item =>
            x.someProperty === Math.floor(item[0].someProperty) &&
            x.anotherProperty === Math.floor(item[0].anotherProperty)));

一个略短的键数组。

const filteredList = list.filter(x =>
    anotherList
        .slice(-6)
        .some(item =>
            ['someProperty', 'anotherProperty'].every(k =>
                x[k] === Math.floor(item[0][k]))));

【讨论】:

  • + 运算符和 parseInt() 不等效。 + 会将'6.66' 转换为6.66,而parseInt() 将转换为6
  • 这成功了!正要问+ 是什么。但现在一切都清除了!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
  • 1970-01-01
相关资源
最近更新 更多