Consider this array:
const arr = [
[1, 2, 3, 4, 3, 2, 4]
,[1, 0, 3, 4, 3, 2, 0]
,[undefined, 0, null, 4, 3, null, 0]
,[undefined, undefined, 5, 7, undefined, null, undefined]
];
My task is to trim each array. Valid values are integers (or floats, same thing). 0 is also considered valid. Trimming in this case means that the array needs to be cropped at the beginning and at the end.
In the examples above:
arr[0] does not need to remove any element
arr[1] does not need to remove any element
arr[2] needs to remove arr[2][0]
arr[3] needs to remove arr[3][0], arr[3][1] from the beginning and arr[3][4], arr[3][5], arr[3][6] at the end.
My approach has been the following:
First find out the first valid element in an array:
const foundStartIndex = arr[x].findIndex(el => el >= 0);
This will help me to slice the array at the beginning.
But how do I find out from where to start removing at the end? There is a "lastIndexOf" but it looks it is not accepting a function the same way "findIndex" does. I could reverse the array, find the first valid element, and calculate where it should be places when it will be reversed back. But maybe there is a better way to do this? Please note that I need to know where, at what index, I need to begin to cut as the index will be used for other reasons.