JavaScript对象数组按属性的最小值进行过滤

编程入门 行业动态 更新时间:2024-10-11 23:26:45
本文介绍了JavaScript对象数组按属性的最小值进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要通过"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对象数组按属性的最小值进行过滤

本文发布于:2023-10-28 01:25:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535089.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   属性   最小值   对象   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!