Select to view content in your preferred language

Attempting to create a data expression, not sure why it won't work

212
2
05-28-2025 01:12 PM
BBooker
New Contributor

I am attempting to get the day counts for incidents that occurred on that date. Really just need it to show how many collectively happened on Monday, Tuesday, etc.. It would also be nice to see if they happened after working hours. This is my code so far:

var portal = Portal("https://www.arcgis.com/");
var fs = FeatureSetByPortalItem(
  portal,
  "b7a7144cda9046a5bfc6b36fa88e0477",
  0,
  ['DateTime'],
  false
);

var dayCounts = {
  "0": 0,
  "1": 0,
  "2": 0,
  "3": 0,
  "4": 0,
  "5": 0,
  "6": 0
};

for (var f in fs) {
  var dateVal = f['DateTime'];
  if (!IsEmpty(dateVal)) {
    var day = Weekday(dateVal) - 1;
    if (HasKey(dayCounts, day)) {
      dayCounts[day] += 1;
    }
  }
}

var outDict = {
  fields: [
    { name: "Day", alias: "Day of Week", type: "esriFieldTypeInteger" },
    { name: "Count", alias: "Incident Count", type: "esriFieldTypeInteger" }
  ],
  geometryType: "",
  features: []
};

// Add the results as features
for (var k in dayCounts) {
  Push(outDict.features, {
    attributes: {
      Day: Number(k),
      Count: dayCounts[k]
    }
  });
};
 
return FeatureSet(Text(outDict));
0 Kudos
2 Replies
KenBuja
MVP Esteemed Contributor

You just need to convert day to a Text string to use it in the HasKey function (line 19).

Note that your original line was "Weekday(dateVal) - 1", which is incorrect. The Weekday function returns the day using values ranging from 0 (Sunday) to 6 (Saturday).

This also only counts that incidents that are outside the hours of 9 am and 5 pm (line 18)

var portal = Portal("https://www.arcgis.com/");
var fs = Top(
  FeatureSetByPortalItem(
    portal,
    "b7a7144cda9046a5bfc6b36fa88e0477",
    0,
    ["DateTime"],
    false
  ),
  10
);

var dayCounts = { "0": 0, "1": 0, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0 };

for (var f in fs) {
  var dateVal = f["DateTime"];
  if (!IsEmpty(dateVal)) {
    if (Hour(dateVal) < 9 || Hour(dateVal) >= 17) {
      var day = Text(Weekday(dateVal));
      if (HasKey(dayCounts, day)) {
        dayCounts[day] += 1;
      }
    }
  }
}

var outDict = {
  fields: [
    { name: "Day", alias: "Day of Week", type: "esriFieldTypeInteger" },
    { name: "Count", alias: "Incident Count", type: "esriFieldTypeInteger" }
  ],
  geometryType: "",
  features: []
};

// Add the results as features
for (var k in dayCounts) {
  Push(
    outDict.features,
    { attributes: { Day: Number(k), Count: dayCounts[k] } }
  );
}

return FeatureSet(Text(outDict));
BBooker
New Contributor

Thank you, I'll try it out soon!

0 Kudos