Obtain a collection of subsets from an array of objects containing either consecutive items or single items with null properties

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.

Answer №1

One way to implement the hash grouping technique is by utilizing the following JavaScript code:

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'}];

let counter = 0;
const result = Object.values(dataSet.reduce((acc, obj) => {
    if (obj.y !== null) {
        counter += 1;
        return acc;
    }

    acc[counter] = acc[counter] ? [...acc[counter], obj] : [obj];
    return acc;
}, {}));

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

Answer №2

Apologies for the confusion, you can iterate through the array and check if the previous data was null.

function findConsecutiveNulls(array, property) {
    let result = [];
    let isPreviousNull = false;
    for (const item of array) {
        if (item[property] === null) {
            if (isPreviousNull) {
                result[result.length - 1].push(item);
            } else {
                result.push([item]);
            }
            isPreviousNull = true;
        } else {
            isPreviousNull = false;
        }
    }
    return result;
}

Example:

const itemsList = [
 {id: '1', value: 'A'},
 {id: '2', value: 'B'},
 {id: '3', value: null}, // <=
 {id: '4', value: null}, // <=
 {id: '5', value: null}, // <=
 {id: '6', value: 'F'},
 {id: '7', value: 'G'},
 {id: '8', value: null}, // <=
 {id: '9', value: null}, // <=
 {id: '10', value: 'J'},
 {id: '11', value: null}, // <=
 {id: '12', value: 'L'} 
];
function findConsecutiveNulls(array, property) {
    let result = [];
    let isPreviousNull = false;
    for (const item of array) {
        if (item[property] === null) {
            if (isPreviousNull) {
                result[result.length - 1].push(item);
            } else {
                result.push([item]);
            }
            isPreviousNull = true;
        } else {
            isPreviousNull = false;
        }
    }
    return result;
}
console.log(findConsecutiveNulls(itemsList, "value"));
.as-console-wrapper {
    max-height: 100% !important;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manipulation of pixels using Three.js software

Looking for guidance on creating a web application that can efficiently manipulate image pixels, specifically from a webcam source. I think using a custom shader in Three.JS could achieve this, but I'm unsure of the process. Can anyone provide assista ...

The functionality of the Ionic menu button becomes disabled once the user has successfully logged in

Having trouble clicking the button after taking a test. Situation: Once logged in -> user takes a test and submits -> redirected to home page. However, unable to click on "Menu button" on the home page. In my Login.ts file: if (this.checker == " ...

Adjust the default color for the icon in the v-text-field type=date using Vuetify

I need to filter records between two dates, displaying data retrieved from the backend. Instead of following the traditional method outlined in Vuetify's date pickers documentation or using the CodePen example: Vuetify v-text-field Date Picker on Cod ...

How to manage UNC paths and "mapped network drives" within an Electron application?

I have developed a cross-platform (macOS-Windows) app using Electron that functions smoothly with files and media assets from a local drive. However, it encounters issues when dealing with UNC paths and "mapped network drives". Since I am a contractor, I d ...

The three.js library encountered an ERROR 404 ( File Not Found ) when trying to import an existing file

Error: GET http://localhost:port/js/three net::ERR_ABORTED 404 (Not Found) I am currently working on a web development project using Three JS. I downloaded the master Zip of ThreeJS from the official website of Three JS I copied the JS files from the Bui ...

The no-unused-expressions rule is triggered when an assignment or function call is expected

I'm just starting out in full stack development and I'm experimenting with coding to improve my understanding of frontend using React JS and Material UI. While working on this component, I encountered an error in the console at line 75 (this.prop ...

Changing a String to an Array of Strings using C

I am attempting to split a string of alphabetically sorted words char *str = "a/apple/arm/basket/bread/car/camp/element/..." into an array of strings in alphabetical order like this: arr[0] = "a/apple/arm" arr[1] = "basket/bread&qu ...

Comparing obj.hasOwnProperty(key) with directly accessing obj[key]

Consider the scenario where I need to determine if a property exists within an Object. A comparison between two methods caught my attention: if(object.hasOwnProperty(key)) { /* perform this action */ } OR if(object[key]) { /* perform this action */ ...

Working with String Arrays: How to eliminate null values

I'm facing an issue with my code. It currently returns 'null' in place of removing x completely and shifting all the other elements to the left. For instance, when I call the function with parameters {"a", "b", "c", "a"} and "a", it should r ...

What is the best way to store information typically saved in a database within a SharePoint folder or the main site directory?

I've been assigned a project at work that falls outside of my usual job description. Despite not being part of the IT/WebDev departments in my company, my team is looking to improve a poorly executed process. Here's what I'm aiming to achiev ...

Using setTimeout within a ForEach loop does not adhere to the specified milliseconds for waiting

Although ForEach console.log's very fast, I am looking to introduce a delay of 8 seconds before logging the next item in Set. I experimented with setTimeout but it doesn't appear to output at the precise milliseconds specified. const completedIds ...

What could be causing my program to not display the elements of my array?

I am currently attempting to display each element of an array on the system. The code snippet below shows how I input the array elements and the issue I am encountering is discussed afterwards. Why are the array elements not being displayed? for (int i ...

Tips for utilizing innerHTML in TypeScript code within an Angular 2 application

Is there a way to utilize innerHTML from TypeScript code in Angular 2 RC4? I'm facing an issue: I need to dynamically add precompiled HTML code when a specific button is clicked. For instance: TypeScript code private addHTML() { // not sure how ...

Utilizing TypeScript with Context API

This is my first time working with Typescript to create a context, and I'm struggling to get it functioning properly. Whenever I try to define interfaces and include them in my value prop, I encounter errors that I can't figure out on my own. Spe ...

Converting PCM raw bytes to audio on an Android device

I have a PCM audio file stored as a byte array with a signed 16 bit little endian format. I'm looking to convert this into a playable format on an Android device running version 3.2 or higher. If anyone has any suggestions on how to achieve this, I wo ...

Having trouble registering for router events in Aurelia using TypeScript

It's puzzling why this isn't functioning as expected:) import {Router, RouterConfiguration} from 'aurelia-router'; import { EventAggregator } from 'aurelia-event-aggregator'; import {autoinject} from 'aurelia-framework&a ...

Tips for accessing the content within a DIV tag in a new browser tab

$('.menu div.profile-btn').on('click', function () { $('.mainservice-page').fadeIn(1200); } The script above effectively displays the contents of the .mainservice-page div, but I would like to open them in a new tab. Is ...

Setting up Redux Saga in a modular format

I am currently using create-react-app for my project. As I now need redux-saga to handle async operations, I am encountering an issue with setting up sagas in a modular manner. When I say modular, I mean having one main sagas file that exports all the comp ...

What methods can be used to search within one array in order to filter another array contained in a list?

Looking for suggestions on creating a filter in one list based on another list How can I handle filtering an array within a list by searching in another array? For example... myArray = [ { "name": "Item-A", "tags": ["Facebook" ...

ajax-jquery request declined

I have a jquery-ajax function that is being called multiple times with different IP addresses each time. This function makes a call to an action in the mvc4 controller responsible for executing a ping and returning the results. After analyzing the request ...