Array of dates -
const WEXDateArray = WEXFile.map((r) => r.Date);
const uniqueDateArray = WEXDateArray.filter((item, pos) => {
return WEXDateArray.indexOf(item) == pos;
});
Date sample -
[
'8/2/2021', '8/3/2021',
'8/4/2021', '8/5/2021',
'8/6/2021', '8/9/2021',
'8/10/2021', '8/11/2021',
'8/12/2021', '8/13/2021',
'8/16/2021', '8/17/2021',
'8/18/2021', '8/19/2021',
'8/20/2021', '8/25/2021',
'8/26/2021', '8/30/2021',
'8/31/2021'
]
arrays of objects -
const WEXFileArraySeparatedByDates: IWEXInterfaceArrayOfArrays =
WEXFile.reduce((r, WEX) => {
r[WEX.Date!] = r[WEX.Date!] || [];
r[WEX.Date!].push(WEX);
return r;
}, Object.create(null));
[
{
Date: '8/30/2021',
'Exec Qty': '15',
'Call/Put': 'P'
},
{
Date: '8/30/2021',
'Exec Qty': '13',
'Call/Put': 'P'
},
{
Date: '8/30/2021',
'Exec Qty': '8',
'Call/Put': 'P'
},
{
Date: '8/30/2021',
'Exec Qty': '14',
'Call/Put': 'P'
},
{
Date: '8/30/2021',
'Exec Qty': '12',
'Call/Put': 'P'
},
{
Date: '8/30/2021',
'Exec Qty': '-75',
'Call/Put': 'P'
{
Date: '8/30/2021',
'Exec Qty': '75',
'Call/Put': 'P'
}
]
[
{
Date: '8/31/2021',
'Exec Qty': '4000',
'Call/Put': 'P'
},
{
Date: '8/31/2021',
'Exec Qty': '2000',
'Call/Put': 'P'
}
]
Explanation - I get CSV file from client and I need to delete objects form the array of objects when 2 rows from the same exec qty return 0 when you sum them up. What I did do is to get a array with the dates only. And created a new object with arrays by the dates. What I could not do is the delete objects by this condition -
if there is on Exec Qty [1, -2, 2, 4, 5, 6, -6]
return [1, 4, 5]
And after that I'll be able to concat the arrays to new array and return the array without the [-2, 2].
So here is where I'm standing right now -
let finalWEXArray: IWEXInterface[] = [];
for (const date of uniqueDateArray) {
finalWEXArray = WEXFileArraySeparatedByDates[date!];
}
How can I filter the arrays by the conditions I mentioned above and store them in the finalWEXArray
Not the most efficient solution, but gets the job done:
for (let i = 0; i< arr.length; i++){
let j = arr.findIndex(x => x.Date === arr[i].Date && +x.qty + +arr[i].qty === 0);
if (j !== -1) {
arr.splice(j, 1)
arr.splice(i, 1)
i--;
}
}
How does it work? It iterates the array, and for each element it checks, if there is an element with the same date but inverse quantity. If such an element is found, remove both. Only increment the index if no element was removed, because otherwise you'd skip some elements in the check.