我有一個包含兩個值的物件陣列:{path: '/index', ip: '123.456.789'}
一些路徑是相同的,ip 也是如此。一些重復,一些獨特的組合。
我想要,對于每個唯一的路徑,附加到該路徑的不同 ip 的數量。因此,例如,可能有 15 個物件帶有path: '/index',但該路徑只有 4 個唯一 ip。
簡單來說,我想找到特定網站頁面的唯一訪問者數量。
希望這是有道理的,非常感謝提前
編輯:
這是我到目前為止所擁有的,以生成非唯一視圖:
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;
};
對于背景關系,輸入是來自路徑/ips 串列的日志檔案的字串
編輯2:
感謝 Peter Seliger,我已經能夠想出我自己的解決方案:
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);
uj5u.com熱心網友回復:
const sampleData = [
{ path: '/index', ip: '123.456.789' },
{ path: '/index/x', ip: '123.456.789' },
{ path: '/index/', ip: '123.456.78' },
{ path: '/index/y', ip: '123.456.789' },
{ path: '/index/', ip: '123.456.89' },
{ path: 'index/', ip: '123.456.9' },
{ path: 'index', ip: '123.456.8' },
{ path: '/index/', ip: '123.456.78' },
{ path: '/index/x/', ip: '123.456.78' },
{ path: 'index/x/', ip: '123.456.7' },
{ path: 'index/x', ip: '123.456.6' },
];
console.log(
sampleData
.reduce((result, { path, ip }, idx, arr) => {
// sanitize/unify any path value
path = path.replace(/^\/ /, '').replace(/\/ $/, '');
// access and/or create a path specific
// set and add the `ip` value to it.
(result[path] ??= new Set).add(ip);
// within the last iteration step
// transform the aggregated object
// into the final result with the
// path specific unique ip count.
if (idx === arr.length - 1) {
result = Object
.entries(result)
.reduce((obj, [path, set]) =>
Object.assign(obj, {
[path]: set.size
}), {}
);
}
return result;
}, {})
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/360911.html
標籤:javascript 数组 打字稿 目的 多维数组
下一篇:從兩個陣列創建一個物件
