How can I extract consecutive objects with a null property from an array of objects? See the example below for more details.
Note:
The
Array.proptype.filter((item) => item.y === null)
method does not solve the problem here. The .filter
method only returns an array of objects where y
is equal to null
.
I am looking to write a method that iterates through each item in the array, checks if the next item also has a null value for y
, and adds the next item to the extracted subset of objects if true. Consecutive items are those that come after each other; if object at index 3 and 4 both have a null y
property, they are considered consecutive items.
If the item at index 8 has a null y
but the items at indexes 7 and 9 do not have a null y
, only the item at index 8 should be added to the extracted subset.
First use case:
The method should be able to identify consecutive nulls and extract them as a subset from the original input set.
Input:
['spider', null, null, null, 'cat','horse', 'eagle']
Output:
[
[null, null, null], <= subset representing nulls between 'spider' and 'cat'
]
Second use case:
The method should also consider single null items and extract them into a separate single-item subset array.
Input:
['spider', null, null, null, 'cat', null, 'horse', 'eagle']
Output:
[
[null, null, null], <== first subset
[null], <== second subset representing null item between 'cat' and 'horse'
]
Extract items from the dataSet with null values for the y
property as shown below.
Output pattern
[
[first subset of consecutive nulls],
[second subset of consecutive nulls],
[....]
]
Please note that the expected output structure is an array of arrays and not an array of objects.
Here's a real-life example with expected output.
The expected output should be an array of arrays containing subsets of the dataSet where the y
property is null and the objects are consecutive.
const dataSet = [
{x: 'foo', y: 'random-y'},
{x: 'bar', y: 'random-y'},
{x: 'yo', y: null}, <=
{x: 'random', y: null}, <=
{x: 'lorem', y: null}, <=
{x: 'ipsum', y: 'random-y'},
{x: 'dolor', y: 'random-y'},
{x: 'var', y: null}, <=
{x: 'mit', y: null}, <=
{x: 'oder', y: 'random-y'},
{x: 'whatever', y: null}, <=
{x: 'something', y: 'random-y'}
];
// Method signature e.g extractSuccesiveNullBy(objectProp: string, from: Array<any>);
extractSuccessiveNullsBy('y', dataSet);
Expected output:
[
[{x: 'yo', y: null}, {x: 'random', y: null}, {x: 'lorem', y: null}],
[{x: 'var', y: null}, {x: 'mit', y: null}],
[{x: 'whatever', y: null}]
]
Any suggestions would be greatly appreciated. Thank you.