I am working with an array of Objects that contain two values:
{path: '/index', ip: '123.456.789'}
. Some paths and IPs are duplicated, while others form unique combinations.
My goal is to determine, for each distinct path, the count of different IPs associated with that path. For example, there may be 15 Objects with path: '/index'
, but only 4 unique IPs for that path.
In simpler terms, I am seeking to find the number of unique visitors to a specific webpage.
I hope this explanation is clear, thank you in advance
Edit:
Here is my current approach to calculate non-unique views:
export const generateViews = (viewData: string): Map<string, number> => {
const pathViewMap: Map<string, number> = new Map();
const viewDataArray = viewData.split("\n");
for (let i = 0; i < viewDataArray.length; i++) {
const [path] = viewDataArray[i].split(" ");
if (path) {
if (pathViewMap.has(path)) {
pathViewMap.set(path, pathViewMap.get(path) + 1);
} else {
pathViewMap.set(path, 1);
}
}
}
return pathViewMap;
};
For more context, the input is a string extracted from a log file containing a list of paths and IPs
Edit 2:
With guidance from Peter Seliger, I have developed my own solution:
const viewDataArray = viewData.split("\n").filter((item) => item);
const arr: { path: string; ip: string }[] = viewDataArray.map(
(line: string) => {
const [path, ip] = line.split(" ");
if (path && ip) {
return { path, ip };
}
}
);
const paths: string[] = Array.from(new Set(arr.map((obj) => obj.path)));
const uniqueViewsMap: Map<string, number> = new Map();
for (let i = 0; i < paths.length; i++) {
const path = paths[i];
const ips = Array.from(
new Set(arr.filter((obj) => obj.path === path).map((obj) => obj.ip))
);
uniqueViewsMap.set(path, ips.length);
}
console.log("==uniqueViewsMap==", uniqueViewsMap);