Loop through an array of arrays in JavaScript. If a match is found, add it to an existing inner array. If not, create a new

I am currently extracting data from a database, and here is a simplified representation of the information:

    var example = [
    {'start': 1966, 'end': 1970},
    {'start': 1969, 'end': 1971},
    {'start': 1972, 'end': 1980},
    {'start': 1974, 'end': 1985},
    {'start': 1975, 'end': 1979},
    {'start': 1986, 'end': 1990},
    {'start': 1991, 'end': 1995}
          ];

My goal is to dynamically sort this data into a new empty array called newArr. After sorting is completed, newArr should be arranged as follows:

var newArr = [
    [
        {'start': 1966, 'end': 1970},
        {'start': 1972, 'end': 1980},
        {'start': 1986, 'end': 1990},
        {'start': 1991, 'end': 1995}
    ],
    [
        {'start': 1969, 'end': 1971},
        {'start': 1974, 'end': 1985}
    ],      
    [
        {'start': 1975, 'end': 1979}
    ]];

As someone who is new to JavaScript, I chose to work with arrays and objects due to the importance of object order in JSON data.

My Approach and Attempts

I have been attempting to group objects based on different keys within the main array (newArr[0], newArr[1], etc.). During iteration over example, if the end property is lower than what is already present in newArr, an overlap occurs, resulting in the creation of a new array. Otherwise, the object should be pushed into the appropriate key without overlap. Below are the three functions I've tried for this process:

    var newArr = [];

    function _overlap(){
    // place first object
    var addFirst = [example[0]];
    newArr.push(addFirst);

    // place others, starting with i = 1;
    for (var i = 1 ; i < example.length ; i++){
        _checkOverlap(example[i]);  
    }   
}   
_overlap();

    function _checkOverlap(input){
    loopJ:{
        for (var j = 0; j < newArr.length; j++){
            var innerArrayLength = newArr[j].length;
            if (input.start > newArr[j][innerArrayLength-1].end ){
                newArr[j].push(input);
                console.log(newArr);
                break loopJ;                    
            } else {
                _createNewArr(input);
                break loopJ;
            }
        }           
    }
}

    function _createNewArr(input){
    var toBeAdded = [];
    toBeAdded.push(input);
    newArr.push(toBeAdded);
}

While this code successfully sorts the first key (newArr0) as intended, it fails to push elements into other keys. I am considering implementing recursion, but multiple crashes due to infinite loops have made this process challenging. Any insights or suggestions would be greatly appreciated.

Answer №1

From my understanding, the process involves searching through each entry in example to find the appropriate group in newArr where the entry can be inserted. If a matching group is found, the entry is added and the iteration moves on to the next entry. If no suitable group is found, a new group is created at the end.

var newArr = [];
outerloop:
for (var entry of example) {
  for (var group of newArr)
    if (group[group.length-1].end < entry.start) {
      group.push(entry);
      continue outerloop;
    }
  newArr.push([entry]);
}

Answer №2

Have you considered utilizing a comparator function within the arr.sort method?

 var sampleArray = [
{'begin': 1966, 'finish': 1970},
{'begin': 1969, 'finish': 1971},
{'begin': 1972, 'finish': 1980},
{'begin': 1974, 'finish': 1985},
{'begin': 1975, 'finish': 1979},
{'begin': 1986, 'finish': 1990},
{'begin': 1991, 'finish': 1995}
      ];

//sorting using comparator function
sampleArray.sort(function(x,y){return x.begin-y.begin}) //will sort based on beginning date

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

Update the default base URL configuration for Axios

My axios configuration looks like this: const configAxios = { baseURL: 'http://127.0.0.1:8000/api', timeout: 30000, }; Vue.prototype.$axios = axios.create(configAxios) When making a call inside my component, I use the following syntax: this ...

Efficiently input text box values into a canvas in real-time using HTML canvas and keypress

There are three text boxes labeled textbox1, textbox2, and textbox3. I am looking to transfer the values entered into these text boxes directly onto a canvas (cnv) whenever a user types in them, and remove the value from the canvas when it is deleted fro ...

The table fails to refresh after adding, modifying, or removing a row

Incorporating ReactJs with Material-UI, I am working on displaying a table of Car components where the display does not update after any Create, Edit, or Delete action has been performed. Below is the structure: class MainCar extends React.Component { c ...

Using Angular's ng-switch directive within a select dropdown option

Can we implement the [Data Presentation Format] to be utilized in the [Dropdown Box]? Specifically, I would like the "parent" items to appear as is within the dropdown, while the "child" items should have a [tab] indentation to denote their relationship wi ...

I am encountering difficulties with generating images on canvas within an Angular environment

I am trying to crop a part of a video that is being played after the user clicks on it. However, I am encountering the following error: ERROR DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may no ...

Tips for setting the textfield value in JSP using Javascript

I am in need of a way to create a random number that will be displayed in the textfield once the user clicks on the "Generate" button. Can someone guide me on how to assign the value of the "output variable" to the "randomNum" textfield? Sample HTML code: ...

Creating a multi-dimensional array in C++ with proper initialization

While reading a book, I came across an example that caught my attention. static int categoryTable[ 2 ][ 2 ][ 2 ] = { //!b!c !bc b!c bc 0, 3, 2, 2, //!a 1, 2, 1, 1 // a }; category = categoryTable[ a ][ b ][ c ] Upon fur ...

Display numbers next to each other

My goal is to display the values next to each other. Below is an example and code of what I am trying to achieve. Can this be done? import requests import json r = requests.get('https://api.website.com',headers = {"content-type": "application/j ...

What is the best way to anchor the components to a specific location on the screen in ASP.NET?

Currently I am working on creating a registration page in asp.net. I have been using panels to group the components such as labels, dropdown lists, and text boxes. However, when I run the page, I noticed that the positions of these components keep changing ...

Verify if the user possesses legitimate Jira REST API credentials

I am currently using the npm module jira-client to send API requests to my Jira system. I need a way to verify whether the user has valid credentials before proceeding. Depending on the validation result, I plan to either: Inform the user that their use ...

"Implementing a dynamic way to assign values to different item types in React

There is an object with multiple values inside: const [sort, setSort] = useState({ "city": [], "price": [], "year": [] }); When the "add" button is clicked, the "city" value should be updated to include certain va ...

When adding margin-left and margin-right, images do not appear in their designated positions

I have a chart displaying images, which are showing up correctly. However, I am facing an issue when I try to add some spacing to the chart by using margin-left and margin-right. Here is the CSS code I included: #chart1 { margin: 0 auto; ...

Problem with reference in .populate()

var mongoose = require('mongoose') mongoose.connect('mongodb://127.0.0.1/DocTest'); var patientsSchema = mongoose.Schema({ //I am attempting to populate this value in the rdvs collection. ssn: String //However, I am experiencing diffi ...

Assign a class to the following element using an Angular 2 Directive

I have a dropdown menu and I want to incorporate an Angular2 directive to control the opening and closing of this dropdown. How can I apply the open class to the latest-notification div, knowing that my directive is applied to the button tag? Below is my ...

Is there a way to navigate to the adjacent values in a json array?

I've been struggling with this issue for quite some time now. I have a list of items that can be moved to a div when clicked. My goal is to navigate through the items in the list (json) by clicking on Next and Previous buttons. As someone who is rela ...

Tips on Handling Multiple Versions of jQuery

I'm seeking your guidance on a particular issue at hand. I am part of the development team for a large web application that heavily relies on jQuery and has been in constant development for the past 7-8 years. Over this time, several versions of jQue ...

Update or Delete BreezeJS EntityManager After Losing Instance Reference

In the process of developing a CRM application with a single-page application structure, I am integrating BreezeJS and AngularJS. The implementation involves utilizing dynamically-generated tabs to display various modules. Each time a user clicks on a menu ...

What is the best way to handle newline characters ( ) when retrieving text files using AJAX?

When using an AJAX call to read a text file, I encountered an issue where it reads the \n\t and backslash symbols. These characters are not needed in the pure text message. How can I ignore or remove them for a clean text display? ...

Display a loading state in Next.js until the page has finished loading completely

When working with a page that includes both getStaticProps and getStaticPaths, you may have noticed that loading the page can take some time, leaving the front-end blank. To enhance the user experience, you might want to display a simple message such as "P ...

Innovative manipulation of arrays using Javascript

Let's say I have some sample input data: data = [ { color : 'Red', number : 5}, { color : 'Blue', number : 3 }, { color : 'Green', age : 8 }, { color : 'Red', number : 7 } ] and I am looking to combine ...