【发布时间】: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