我想實現一個陣列上的filter方法,其中每個元素都是一個對象是這樣的:如何過濾和計算javascript數組中的對象?
{
"start": 1234,
"end": 4321,
"count": 0
}
我想從我的數組中刪除重複而遞增count
財產。
目前,我只設法陣列由start
財產使用此代碼進行過濾:
var temp = {};
myArray = myArray.filter(function(obj) {
if (obj.start in temp) {
return false;
} else {
temp[obj.start] = true;
return true;
}
});
我想實現的是,在這些條件下工作(爲了更好地解釋一個過濾器,我會參考在temp
元件tempObj
和當前對象爲obj
):
- 如果
obj.start
===tempObj.start
& &obj.end
===tempObj.end
,obj.count
+ = 1- 如果
obj.start
===tempObj.start
||obj.end
===tempObj.end
,obj.count
tempObj.count
= + 1- 如果
obj.start
>tempObj.start
& &obj.end
<tempObj.end
,obj.count
tempObj.count
= + 1- 別的添加新的元件,以與
temp
count
= 1
可以使用過濾方法嗎?如果不是,那麼正確的方法是什麼?我寧願不使用任何框架。
編輯:根據RobG請求,使問題更清楚我添加一個輸入和輸出示例。
例輸入:
myArray = [{
"start": 1105,
"end": 1501,
"count": 0
},
{
"start": 1105,
"end": 1003,
"count": 0
},
{
"start": 1110,
"end": 1120,
"count": 0
},
{
"start": 1105,
"end": 1003,
"count": 0
},
{
"start": 1115,
"end": 1120,
"count": 0
}]
所需的輸出:
myArray = [{
"start": 1105,
"end": 1501,
"count": 1
},
{
"start": 1105,
"end": 1003,
"count": 3
},
{
"start": 1110,
"end": 1120,
"count": 1
}
{
"start": 1115,
"end": 1120,
"count": 1
}]
你的問題不明確(對我來說)。你能提供樣本輸入和輸出嗎?你想刪除「重複」(不說什麼定義重複),但*過濾器*創建一個新的數組,它不會修改被過濾的數組。 – RobG
@RobG重複是具有相同的開始和結束的陣列中的一個或多個對象的對象。我會盡快提供所需 – elegali
的信息。由於你的結果是將輸入的不同,我建議使用* *減少和你去建立新的陣列,增加新的元素和更新沿途現有的。你也可以使用* forEach *,但* reduce *更具語義。 – RobG