-1

I have a JSON array in a local file called data.json, looks the following:

[
    {
        "id":"1",
        "priority": "P1",
        "start_date": "2021-01-01 14:40:33"
    },{
        "id":"2",
        "priority": "P2",
        "start_date": "2019-01-01 14:40:33"
    },{
        "id":"3",
        "priority": "P3",
        "start_date": "2020-01-01 14:40:33"
    },{
        "id":"4",
        "priority": "P2",
        "start_date": "2020-01-01 14:40:33"
    },{
        "id":"5",
        "priority": "P1",
        "start_date": "2021-01-01 14:40:33"
    }
]

I'm trying to get total count set by two conditions as seen below, however the formatting on the start_date YYYY-MM-DD HH-MM-SS is static and can't be changed, I want to be able to look for the first 4 digits only (the year) but still unable to, any toughts?

import data from "./data.json" assert{ type: "json" };

    var count = 0;
    for (var i = 0; i < data.length; i++) {
        if ((data[i].priority === 'P1') && (data[i].start_date === "2021")) {
            count++;
        }
    }
    console.log(count)
mabo
  • 27
  • 3

1 Answers1

1

What about instead using String.prototype.startsWith:

import data from "./data.json";

let count = 0;

for (let i = 0; i < data.length; i++) {
  if (data[i].priority === "P1" && data[i].start_date.startsWith("2021")) {
    count++;
  }
}

console.log(count);

You could also try instead using Array.prototype.filter:

const count = data.filter(
  item => item.priority === "P1" && item.start_date.startsWith("2021")
).length;
   

Or with destructuring:

const count = data.filter(
  ({ priority, start_date }) =>
    priority === "P1" && start_date.startsWith("2021")
).length;
Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
  • Thanks Alexander, that seems to work, I'm fairly new to programming in general, do you see any downside of using my approach? – mabo Oct 08 '21 at 15:15
  • "2021" will never match "2021-01-01 14:40:33" for example. – Andy Oct 08 '21 at 15:25