我需要通过"rest"属性的最小值来过滤此对象数组.这是做到这一点的一种方法.还有其他方法吗?
I need to filter this object array by minimum value of 'rest' attribute. This is an one way to do it. Is there any other ways ?
'data'变量是链接函数的结果.还有什么其他方法可以在Math.min()函数中再次调用数据"变量而不会.
'data' variable is a result of chained function. Is there any other way to do this without calling 'data' variable again inside Math.min() function.
let data = [ { size: 5, qty: 2, rest: 0 }, { size: 2, qty: 5, rest: 0 }, { size: 1, qty: 10, rest: 0 }, { size: 3, qty: 3, rest: 1 }, { size: 4, qty: 2, rest: 2 } ] let result = data.filter(e=> e.rest === Math.min(...data.map(f=>f.rest) ) ); console.log(result); // result is //[ { size: 5, qty: 2, rest: 0 }, // { size: 2, qty: 5, rest: 0 }, // { size: 1, qty: 10, rest: 0 }] 推荐答案
imo.最简单/最好的解决方案是@CertainPerformance给您的解决方案.
imo. the simplest/best solution is the one @CertainPerformance gave you.
只是想添加具有线性运行时的另一种解决方案(实际上仅在数组上迭代一次)
Just wanted to add another solution with linear runtime (that truly iterates only once over the Array)
let data = [ { size: 5, qty: 2, rest: 0 }, { size: 2, qty: 5, rest: 0 }, { size: 1, qty: 10, rest: 0 }, { size: 3, qty: 3, rest: 1 }, { size: 4, qty: 2, rest: 2 } ]; let result = data.reduce((result, item) => { let minRest = result.length? result[0].rest: item.rest; if (item.rest < minRest) { minRest = item.rest; result.length = 0; } if (item.rest === minRest) { result.push(item); } return result; }, []); console.log(result);
@ mathieux51让我有了另一个想法,知道如何在方法链中执行此操作,但是其可读性/清晰度/意图不如其他方法好:
@mathieux51 got me another idea how you can do this inside a method chain, but the readability/clarity/intention is not as good as with the other approaches:
let data = [ { size: 5, qty: 2, rest: 0 }, { size: 2, qty: 5, rest: 0 }, { size: 1, qty: 10, rest: 0 }, { size: 3, qty: 3, rest: 1 }, { size: 4, qty: 2, rest: 2 } ]; let result = data.sort((a, b) => a.rest - b.rest) .filter((item, index, array) => item.rest === array[0].rest); console.log(result);
更多推荐
JavaScript对象数组按属性的最小值进行过滤
发布评论