Is there a way to retrieve keys with distinct values in an array of objects using JavaScript?

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);

Answer №1

const data = [
  { url: '/home', ip_address: '123.456.789' },
  { url: '/home/about', ip_address: '123.456.789' },
  { url: '/home/', ip_address: '123.456.78' },
  { url: '/home/contact', ip_address: '123.456.789' },
  { url: '/home/', ip_address: '123.456.89' },
  { url: 'home/', ip_address: '123.456.9' },
  { url: 'home', ip_address: '123.456.8' },
  { url: '/home/', ip_address: '123.456.78' },
  { url: '/home/about/', ip_address: '123.456.78' },
  { url: 'home/about/', ip_address: '123.456.7' },
  { url: 'home/about', ip_address: '123.456.6' },
];
console.log(
  data
    .reduce((result, { url, ip_address }, idx, arr) => {

      // sanitize/unify any URL value
      url = url.replace(/^\/+/, '').replace(/\/+$/, '');

      // access and/or create a URL specific
      // set and add the `ip_address` value to it.
      (result[url] ??= new Set).add(ip_address);

      // within the last iteration step
      // transform the aggregated object
      // into the final result with the
      // URL specific unique IP address count.      
      if (idx === arr.length - 1) {
        result = Object
          .entries(result)
          .reduce((obj, [url, set]) =>
            Object.assign(obj, {
              [url]: set.size
            }), {}
          );
      }
      return result;

    }, {})
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I encountered an issue when trying to launch my React application, as the CMD displayed an npm error message stating 'npm error! missing script:start'. Can someone offer assistance with this problem?

view image details Despite spending countless hours searching through past responses and attempting to resolve this issue, I have been unsuccessful. Upon entering 'npm create-react-app' in the terminal and navigating to the correct directory, I ...

SignalR enables the display of identical dashboard data pulled from queries on various browsers. By utilizing SignalR/hub, MVC, and C#.NET, the data can

Encountering an issue with my signalr/hub while fetching dashboard data. I'm using 2 browsers to access data based on dates. However, when searching for July on browser 1 and then switching to another month on browser 2, the data in browser 1 gets upd ...

A More Straightforward Approach to Unsubscribing from Observables in Angular 7

Is there a way to simplify the process of automatically unsubscribing from Observables when a component is destroyed using takeUntil? It becomes tedious having to repeat the same code in multiple components. I am looking for a solution that allows me to a ...

How do browsers typically prioritize loading files into the cache?

Out of curiosity, I wonder if the categorization is determined by file names or byte code? It's possible that it varies across different browsers. Thank you! ...

Is it possible to clear/reset the file input when the page is loaded?

One of my tasks involves clearing a file upload input field when the page is loaded. I've searched through 10-15 different ways on stackoverflow to accomplish this, but every solution requires a reset button which doesn't meet my requirement of a ...

What is the method for utilizing OR statements in Playwright assert?

How can I verify whether the text content is either one or two using Playwright? await expect(this.header).toHaveText('one').or('two') Is there a way to achieve this functionality in Playwright? Additionally, can this feature be inco ...

personalized options for initiating and concluding html audio component

I am currently facing an issue with my html audio element that plays a track. The setup is quite straightforward: <audio controls loop="loop"> <source type="audio/wav" src="song.wav"> </audio> However, I need to create custom start ...

Issue Arising from Printing a Custom Instruction in a Schema Generated Document

When dynamically adding a directive, the directive is correctly generated in the output schema. However, it seems to be missing when applied to specific fields. Here is how the directive was created: const limitDirective = new graphql.GraphQLDirective({ na ...

Tips for enabling both vertical and horizontal scrolling using the mousewheel on a webpage

Our website features a unique scrolling functionality where it starts off vertically and then switches to horizontal once the user reaches the bottom. This allows for a seamless transition between scrolling directions. In addition, users can easily naviga ...

Python: Dividing and dividing

My current project involves creating a command prompt using Python. One of the challenges I'm facing is splitting a text file into lines and then further splitting them into strings. Here's an example: Original text to split: command1 var1 va ...

Data loss from AngularJS multipartForm directive when redirecting to different routes

Having trouble with an Excel file uploader and data parsing in the routes? It seems like the FormData is getting lost when sent through the $http service route. Any advice or experience on how to handle this issue would be greatly appreciated! Html View: ...

Utilizing the power of jQuery within three.js

Thank you once again for your previous assistance, but I find myself in need of your expertise once more. I have successfully added markers to my map as desired. However, these markers now require functionality to be clickable. Specifically, when clicked, ...

JavaScript can be used to track the number of elements added to an input box by detecting when a key is pressed, but not yet released

How can I use JavaScript or Angular to count the number of characters entered in an input box when a key, like 'a', is pressed but not released on the keyboard? <input type="text" name="charactercount" value="aaaaaa&qu ...

Conceal the object, while revealing a void in its place

Is there a way to hide an image but keep the containing div blank with the same dimensions? I want it to appear as if no content was there, maintaining the original width and height. For example: http://jsfiddle.net/rJuWL/1/ After hiding, "Second!" appea ...

What is the best method for determining the height of a sandboxed iframe?

My website includes an iframe with the sandbox attribute. Users can set the content of this iframe directly through the 'srcdoc' attribute, which raises security concerns. I am trying to find a way to dynamically adjust the height of the iframe ...

Unlock real-time alerts with the power of JavaScript and PHP!

I am currently working on enhancing my skills in javascript. I have a basic idea of what I want to achieve. My goal is to create an automated javascript function that accesses a php page. This php page will create an array of new notifications for the ja ...

Morris.js tutorial: Enhancing bar charts with data labels

I have this: https://i.sstatic.net/GXjur.png But I want this instead: https://i.sstatic.net/spcS2.png Does morris.js support this feature? If not, what would be the most effective method to implement it? ...

What is the process of setting a function as a property value in the Vuex State of an object from a component?

Can someone assist me with incorporating a function into the property of an object as a value for the state in my Vuex store? I am currently restructuring some code for a website using vue.js and fullpage.js. I have moved my fullpage options to the vuex s ...

Sum all of the property values in an array using Vue.js

I'm currently developing a small app and have an array of objects with two properties each: 'label' and 'value'. I want to calculate the total value by adding up all the values in the 'value' property. Vue/JS data() { ...

JavaScript: When setting focus on a DOM element, the document.activeElement is not automatically updated

I am facing an issue where I need to manually set focus on two buttons consecutively. These buttons are jQuery-Objects stored in an array named pMenus. Below is the code snippet: function OpenSubMenus(pMenus) { pMenus[pMenus.length - 1].get(0).focus() ...