简体   繁体   中英

How can I get keys with unique values in an array of objects? (JavaScript)

I have an array of Objects containing two values: {path: '/index', ip: '123.456.789'} Some of the paths are the same, as are the ip's. Some duplicates, some unique combinations.

I want, for each unique path, the number of different ip's attached to that path. So, for example, there may be 15 Objects with path: '/index' , but only 4 unique ip's for that path.

In simpler terms, I want to find the amount of unique visitors to a particular website page.

Hope this makes sense, many thanks in advance

Edit:

Here is what I have so far, to generate 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 context, the input is a string that comes from a log file of a list of paths/ips

 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; }, {}) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM