我把一些东西放在一起,代码如下所示:
objectives.filter(function (x) {
return x.examId == exam;
}).reduce(function (accumulator, current) {
if (!accumulator.some(function (x) { return x.id == current.id; })) {
accumulator.push(current);
}
return accumulator;
}, []).map(function (x) {
return {
id: x.id,
text: x.text,
numberAndtext: x.numberAndText
}
});
(“唯一符”的灵感来自https://stackoverflow.com/a/17903018/2022183 https://stackoverflow.com/a/17903018/2022183).
您可以通过使用如下函数提取属性与常量值的比较来缩短此代码:
function propertyEqualTo(prop, val) {
return function (x) {
return x[prop] == val;
};
}
你的代码将显示为:
return objectives.filter(propertyEqualTo('examId', exam)).reduce(function (accumulator, current) {
if (!accumulator.some(propertyEqualTo('id', current.id)) {
accumulator.push(current);
}
...
您确定您需要uniq()
无论如何都打电话到这里吗?您正在匹配一个id
从一开始就应该是独一无二的。如果您能够删除此调用,您的代码应该非常短。