What is the best way to split a JSON array into two separate JSON arrays?

Greetings, I have received a JSON response.

   response.data: [{
        "id": 1,
        "datefrom": "2018-08-30 11:21:25",
        "dateto": "2018-08-31 11:21:25",
    }, {
         "id": 2,
        "datefrom": "2018-08-30 11:21:25",
        "dateto": "2018-08-31 11:21:25",
    }, {
        "id": 3,
        "datefrom": "2018-09-01 11:21:25",
        "dateto": "2018-09-03 11:21:25",
    }, {
         "id": 4,
        "datefrom": "2018-09-02 11:21:25",
        "dateto": "2018-09-03 11:21:25",
    }, {
         "id": 5,
        "datefrom": "2018-09-03 11:21:25",
        "dateto": "2018-09-04 11:21:25",
    }]

I am looking to split this JSON data into two based on the 'datefrom' column if 'datefrom' < "2018-08-31 11:21:25".

The divided JSON data should look like this:

json1: [{
        "id": 1,
        "datefrom": "2018-08-30 11:21:25",
        "dateto": "2018-08-31 11:21:25",
    }, {
         "id": 2,
        "datefrom": "2018-08-30 11:21:25",
        "dateto": "2018-08-31 11:21:25",
    }]

and

json2:[{
        "id": 3,
        "datefrom": "2018-09-01 11:21:25",
        "dateto": "2018-09-03 11:21:25",
    }, {
         "id": 4,
        "datefrom": "2018-09-02 11:21:25",
        "dateto": "2018-09-03 11:21:25",
    }, {
         "id": 5,
        "datefrom": "2018-09-03 11:21:25",
        "dateto": "2018-09-04 11:21:25",
    }]

Would appreciate guidance on how to achieve this using JavaScript.

I have attempted the following:

if(datediff<120000){


        values.push(response.data[i]['datefrom']);
         Object.assign(values, {datefrom: response.data[i]['datefrom']});
        values.push(response.data[i]['checkout']);
         Object.assign(values, {dateto: response.data[i]['dateto']});
        console.log(values)
        $rootScope.expesscheckindata1= values;

      else{
        values1.push(response.data[i]['datefrom']);
        Object.assign(values1, {datefrom: response.data[i]['datefrom']});
        values1.push(response.data[i]['checkout']);
        Object.assign(values1, {dateto: response.data[i]['dateto']});
         console.log(values1)
        $rootScope.expesscheckindata2= values1;

However, during the process, the data gets appended as the next data like ["2018-08-30 11:21:25", "2018-08-31 11:21:25", "2018-08-29 00:00:00", "2018-08-30 00:00:00", datefrom: "2018-08-29 00:00:00", dateto: "2018-08-30 00:00:00"]

Answer №1

To compare the value of response.data[index].datefrom and then add it to an empty array, you can use json1 and json2 depending on the value.

var response = {};
response.data = [{
        "id": 1,
        "datefrom": "2018-08-30 11:21:25",
        "dateto": "2018-08-31 11:21:25",
    }, {
         "id": 2,
        "datefrom": "2018-08-30 11:21:25",
        "dateto": "2018-08-31 11:21:25",
    }, {
        "id": 3,
        "datefrom": "2018-09-01 11:21:25",
        "dateto": "2018-09-03 11:21:25",
    }, {
         "id": 4,
        "datefrom": "2018-09-02 11:21:25",
        "dateto": "2018-09-03 11:21:25",
    }, {
         "id": 5,
        "datefrom": "2018-09-03 11:21:25",
        "dateto": "2018-09-04 11:21:25",
    }];
    
    var json1=[];
    var json2=[];
    
for(i=0; i<response.data.length; i++){
if(response.data[i].datefrom < '2018-08-31'){
json1.push(response.data[i]);
}else{
json2.push(response.data[i]);
}
}


console.log("JSON1: ");
console.log(json1);
console.log("JSON2: ");
console.log(json2);

Answer №2

Implement a function that loops through the array and retrieves the index of dates that exceed the specified date.

Once you have obtained this index, using response.data.slice(index, response.data.length) will give you array2, while slice(0, index) will provide you with array1.

Answer №3

Below is the requested function:

var arr=[{
        "id": 1,
        "datefrom": "2018-08-30 11:21:25",
        "dateto": "2018-08-31 11:21:25",
    }, {
        "id": 2,
        "datefrom": "2018-08-30 11:21:25",
        "dateto": "2018-08-31 11:21:25",
    }, {
        "id": 3,
        "datefrom": "2018-09-01 11:21:25",
        "dateto": "2018-09-03 11:21:25",
    }, {
         "id": 4,
        "datefrom": "2018-09-02 11:21:25",
        "dateto": "2018-09-03 11:21:25",
    }, {
         "id": 5,
        "datefrom": "2018-09-03 11:21:25",
        "dateto": "2018-09-04 11:21:25",
    }]


var before=[], after=[]
function splitByDate(date){
  arr.map(function(item){
    (new Date(item.datefrom)<new Date(date))?before.push(item):after.push(item)
  })
}
//calling the function

splitByDate("2018-08-31 11:21:25")

//Printing the Output
console.log(before)
console.log("-------------------------")
console.log(after)

Answer №4

To achieve the desired outcome, you can utilize the reduce() method of arrays and the Date.parse() function to compare dates with the current date.

Check out this DEMO:

const data=[{"id":1,"datefrom":"2018-08-30 11:21:25","dateto":"2018-08-31 11:21:25"},{"id":2,"datefrom":"2018-08-30 11:21:25","dateto":"2018-08-31 11:21:25"},{"id":3,"datefrom":"2018-09-01 11:21:25","dateto":"2018-09-03 11:21:25"},{"id":4,"datefrom":"2018-09-02 11:21:25","dateto":"2018-09-03 11:21:25"},{"id":5,"datefrom":"2018-09-03 11:21:25","dateto":"2018-09-04 11:21:25"}];

let result = data.reduce((r, o) => {
    let index = Date.parse(o.datefrom) < Date.now() ? 0 : 1;
    r[index].push(o);
    return r;
}, [ [],[] ]);

console.log(result[0],'\n\n',result[1])
.as-console-wrapper {max-height: 100% !important;top: 0;}

Answer №5

To start, you need to convert the JSON into a JavaScript object.

This can be achieved using the built-in JSON class in JavaScript:

var jsObj = JSON.parse(json);

As the root of your JSON is a JSON array, jsObj will be a JavaScript Array.

JavaScript arrays come with useful methods for manipulation and traversal.

Learn more about Javascript Arrays here

By referring to the documentation, you will discover Array.prototype.findIndex and Array.prototype.slice

Array.prototype.findIndex takes a predicate as an argument, which is a function executed for each element in the array and should return true when the desired element is found:

var refTime = new Date('2018-08-31 11:21:25').getTime();
var index = jsObj.findIndex(function(elem) {
    var currentTime = new Date(elem.datefrom).getTime();
    // returns true when encountering the first date > refDate
    return currentTime > refTime;

});
let result = jsObj;
// if findIndex returns -1, no elements satisfy the predicate, so result remains the original array (jsObj)
if (index !== -1) {
    // divide the array around the found index into two resulting arrays
    result = [jsObj.slice(0, index), jsObj.slice(index)];
}

It's important to note that this code assumes the array elements are sorted by datefrom in ascending order. If not, you must sort the array first in ascending order like this:

jsObj.sort((e1, e2) => {
    var time1 = new Date(e1.datefrom).getTime();
    var time2 = new Date(e2.datefrom).getTime();
    return Math.sign(time1 - time2);
});

Others may have suggested iterating through the array and populating resulting arrays based on conditions, but this answer focuses on dividing an array using standard manipulation tools.

See working fiddle here (check console for results)

Explore Array.prototype.slice, Array.prototype.findIndex, and Array.prototype.sort

Answer №6

 

const data = [
    {
        id: 1,
        datefrom: '2018-08-30 11:21:25',
        dateto: '2018-08-31 11:21:25',
    },
    {
        id: 2,
        datefrom: '2018-08-30 11:21:25',
        dateto: '2018-08-31 11:21:25',
    },
    {
        id: 3,
        datefrom: '2018-09-01 11:21:25',
        dateto: '2018-09-03 11:21:25',
    },
    {
        id: 4,
        datefrom: '2018-09-02 11:21:25',
        dateto: '2018-09-03 11:21:25',
    },
    {
        id: 5,
        datefrom: '2018-09-03 11:21:25',
        dateto: '2018-09-04 11:21:25',
    },
];
var json1 = [];
var json2 = [];
$.each(data, function(index, value) {
    if (value.datefrom == '2018-08-31 11:21:25') {
        json1.push(value);
    } else {
        json2.push(value);
    }
});
console.log("one",json1);
console.log("two",json2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №7

Utilize the filter method:

data = [
    {
        id: 1,
        datefrom: '2018-08-30 11:21:25',
        dateto: '2018-08-31 11:21:25',
    },
    {
        id: 2,
        datefrom: '2018-08-30 11:21:25',
        dateto: '2018-08-31 11:21:25',
    },
    {
        id: 3,
        datefrom: '2018-09-01 11:21:25',
        dateto: '2018-09-03 11:21:25',
    },
    {
        id: 4,
        datefrom: '2018-09-02 11:21:25',
        dateto: '2018-09-03 11:21:25',
    },
    {
        id: 5,
        datefrom: '2018-09-03 11:21:25',
        dateto: '2018-09-04 11:21:25',
    },
];

console.log(
    "Filtering smaller dates",
    data.filter(
        item=>
            item.datefrom.localeCompare("2018-08-31 11:21:25")===-1
    )
);
console.log(
    "Filtering bigger dates",
    data.filter(
        item=>
            item.datefrom.localeCompare("2018-08-31 11:21:25")!==-1
    )
);

const splitByDate = (date,array) =>
  array.reduce(
    (result,item)=>{
      (new Date(item.datefrom).getTime())<date.getTime()
        ? result[0].push(item)
        : result[1].push(item);
      return result;
    },
    [[],[]]//initial result
  );
const [low,high] = splitByDate(new Date('2018-08-31 11:21:25'),data)

console.log(
  "Dates before reference date",
  low,
  "Dates after reference date",
  high
);

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

Neglecting the error message for type assignment in the Typescript compiler

Presented here is a scenario I am facing: const customer = new Customer(); let customerViewModel = new CustomerLayoutViewModel(); customerViewModel = customer; Despite both Customer and CustomerLayoutViewModel being identical at the moment, there is no ...

What are some methods to maintain consistent height for each list item in an unordered list on small screens like mobile devices?

While vh works well for larger screen sizes such as laptops, it may not maintain the height of the li on smaller devices like mobiles. Is there a better approach than relying on media queries to achieve responsiveness across different screen sizes? ...

Update elements dynamically using JSX

I have an array called data.info that gets updated over time, and my goal is to replace placeholder rendered elements with another set of elements. The default state of app.js is as follows: return ( <Fragment> {data.info.map((index) =&g ...

Using the PHP mail() function to send emails to all users listed in the clients.json file

I have a question about sending emails to all users listed in my JSON file. Can someone please help me figure out how to make this work so that when I click on send, the email gets sent? Thank you in advance! Here is the code I'm working with: <?p ...

Node.js Express - Run a function on each incoming HTTP request

My local Node.js server has a function called unzip() that is responsible for downloading a .json.gz file from an AWS CloudFront URL () and unzipping it into a .json file whenever the server is started with node app.js. Prior to responding to routes, the ...

C program that will output all the elements contained in each structure within an array of structures

I've been working on a function in C that is supposed to take an array of structs, each holding employee information, and then print out all the details for each struct. However, I'm not getting any output from my code. Can anyone help me trouble ...

Guide to implementing a variable delay or sleep function in JQuery within a for loop

I've noticed that many people have asked similar questions, but none of the solutions provided seem to work in my specific case. My goal is to incorporate a delay within a for loop with varying time lengths. These time lengths are retrieved from an a ...

Modify the background color of one div based on the visibility of another div

My carousel consists of three divs representing a Twitter post, a Facebook post, and a LinkedIn post. These are contained within another div called #social-media-feeds. I am curious if it is feasible to adjust the background color of #social-media-feeds d ...

Extracting data from an array within a JSON payload

Currently, I am working on a REST API that is being used in an Angular project. The response is coming back in the following format: Although I am able to retrieve the short description, I am facing an issue when trying to display it using *ngFor loop. As ...

Trouble with setInterval not refreshing the HTML element

I'm currently working on a script that should update the value of an element every second. However, I've encountered an issue where the element only updates the first time and then stops. Strangely, there are no errors appearing in the console ei ...

storing HTML elements in Chrome's cache

I have developed a content uploading module that utilizes the file API. The HTML code is <input type="file" id="filepicker-input" multiple="true" style="display:none;"/> <div class="addfile_btndiv" id="addfile_btndiv"> ...

Setting a JavaScript value for a property in an MVC model

I am currently working on an asp.net mvc application and I am in the process of implementing image uploading functionality. Below is the code for the image upload function: $(document).ready(function () { TableDatatablesEditable.init(); ...

Looking for a list of events in Express.js?

I've been searching through the official documentation, but I couldn't find a list of events for express. Does anyone know if there's something like 'route-matched' so that I can use app.on('route-matched', () => {})? ...

Incorporating the Material UI App Bar alongside React Router for an enhanced user

For my web development course project, I am venturing into the world of JavaScript and React to create a website. Utilizing Material UI's appbar for my header design, I have successfully incorporated react router to enable navigation on my site. Howev ...

Enhancing JavaScript Variables Through Dynamic Ajax/PHP Interaction

I've been encountering some difficulties when trying to refresh my game. Initially, I attempted echoing the entire script each time... but that method was not aesthetically pleasing. Currently, I am experimenting with updating the variables through an ...

Beginning your journey with Mock server and Grunt

Although I have gone through the documentation available at , I am still struggling to get the mockserver up and running despite spending hours on following the instructions provided in the guide. Could someone please outline the precise steps or identify ...

Experiencing issues with the Google Drive file selection API due to JavaScript

I am having trouble implementing a Google file picker in my Django Project. Every time I try to create an HTML page with an integrated Google file picker, I encounter a 500 "Something went wrong" error. https://i.sstatic.net/6JMh7.png This issue arises a ...

Ensuring continuous execution of JS EventListener

The other day, I received a solution from someone on this platform for a script that changes the color of a div when scrolling. Here is the code I implemented: const x = document.getElementById("menuID"); window.addEventListener("scroll", () => { ...

Issues stemming from cross-domain AJAX have resulted in errors with Karma and Jasmine

I've been working on configuring tests that utilize Jasmine and Karma to test my JavaScript code. Karma operates in Node.js and initiates a Chrome browser for testing purposes. Unfortunately, I keep encountering an error message that reads "Chrome 28 ...

Unforeseen alterations in value occur in JavaScript when converting to JSON format

Having trouble generating a gantt chart from a JSON string, specifically with parsing the JSON string into a JSON object. I have a variable myString containing a JSON string that looks like this: {"c": [{"v": "496"}, {"v": "Task name 1"}, {"v": "9, "}, { ...