Javascript 将数组过滤为多个子集的优化方法
我有这个数组Javascript 将数组过滤为多个子集的优化方法,javascript,arrays,filter,Javascript,Arrays,Filter,我有这个数组 const array = [ {value: 1, selected: false, highlighted: true}, {value: 3, selected: true, highlighted: true}, {value: 4, selected: false, highlighted: false}, {value: 2}, selected: true, highlighted: false ] 我想从上面生成三个子集数组,它们是高亮显示的、选中的和选中的
const array = [ {value: 1, selected: false, highlighted: true},
{value: 3, selected: true, highlighted: true},
{value: 4, selected: false, highlighted: false},
{value: 2}, selected: true, highlighted: false ]
我想从上面生成三个子集数组,它们是高亮显示的、选中的和选中的HightLighted
我可以使用array.filter方法实现这一点,如下所示
const selected = array.filter((i) => i.selected)
const highlighted = array.filter((i) => i.highlighted)
const selectedHighlighted = array.filter((i) => i.selected && selectedHighlighted)
我的问题是如何以最佳方式实现这一点,上面的代码有3个循环,如果我使用类似于forEach方法的方法,检查其中的条件,并将对象推送到相应的数组,这不是比上述方法更优化的方法吗?如果我使用类似于forEach方法的方法,检查其中的条件,然后将对象推到相应的数组中,当然,没有什么能阻止您编写相应的代码..?您所描述的比上面的代码@abidh更好