[英]Filter object values in array
我已經對對象數組進行了排序:
const arr = [
{
"persentage": "30",
"value": "123"
},
{
"persentage": "27",
"value": "345"
},
{
"persentage": "2",
"value": "232"
},
{
"persentage": "2",
"value": "343"
},
{
"persentage": "9",
"value": "4334"
},
{
"persentage": "6",
"value": "43343"
},
{
"persentage": "4",
"value": "95"
},
];
如果百分比總和超過 90,我需要按 2 個條件過濾它,我應該跳過其他對象,或者如果對象數大於 6,那么我也應該跳過其余對象。 我有下一個解決方案:
let arr2 = [];
const MAX_PESENTAGE = 90;
const MAX_TOP_VALUES = 6;
let accumulatePersentage = 0;
let countOfValue = 0;
for(const elem of arr) {
accumulatePersentage += Number(elem.persentage);
countOfValue++;
if(accumulatePersentage >= MAX_PESENTAGE || countOfValue > MAX_TOP_VALUES) {
break;
}
arr2.push(elem);
}
console.log(arr2)
但我不確定這是最好的解決方案嗎?
你可以像這樣使用reduce
:
const arr = [ { "persentage": "30", "value": "123" }, { "persentage": "27", "value": "345" }, { "persentage": "2", "value": "232" }, { "persentage": "2", "value": "343" }, { "persentage": "9", "value": "4334" }, { "persentage": "6", "value": "43343" }, { "persentage": "4", "value": "95" } ]; const filtered = arr.reduce((acc, item, i) => { acc.percentage += Number(item.persentage); if (acc.percentage <= 90 && i < 6) { acc.items.push(item); } return acc; }, {percentage: 0, items: []}).items; console.log(filtered);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.