Incorporating unique numbers in the map reduce process

I have a CSV file containing information on which numbers called each other and the details of the calls like duration, time, etc.

My goal is to compile all the numbers that a specific number has called into an array. Each element in this array should be a document containing all the call details as well. Essentially, I need a list of documents with a "caller" number and a nested "called" array.

To achieve this, I initially thought of using a map reduce solution, which seemed quite straightforward. However, I am facing an issue where the resulting array includes duplicate numbers instead of unique ones during the reduce phase.

The current map reduce script I'm using is as follows (executed in the Mongo shell):

db.contacts.mapReduce(
  function(){
    numbers = [];
    value={phone:this.<<called_number>>};
    numbers.push(value);
    emit(this.<<caller_number>>,{called:numbers});
  },
  function(key,values) {
    result={called:[]};
    values.forEach(function (v) {
      var i,j;
      for(i=0;i<v.called.length;i++) {
        var flag=0;
        for(j=0;j<result.called.length;j++) {
          if(v.called[i].phone==result.called[j].phone){
            flag=1;
          }
        }
        if(flag==0) {
          result.called.push(v.called[i])
        }
      }
    });
    return result;
  },
  {"query": {},"out":"new_collection"}
)

I understand that both the map and reduce functions are written in JavaScript. Any help from experienced JavaScript coders on optimizing the reduce function to only consider unique numbers would be greatly appreciated.

Answer №1

Check out this new solution.

db.contacts.mapReduce(function(){
     emit(this.<<caller_number>>, {called:this.<<called_number>>, callDuration:this.<<callDuration>>,...});}
    ,function(key,values)
      {
      var map = {};
      var called=values.filter(function removeDuplicated(it){
          if (!map[it.called]){
              map[it.called] = 1;
              return true;
          }
          return false;
      })
      return {caller:key, called:called};},
    {"query": {},"out":"new_collection"})

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

In JavaScript with Node.js, how can one verify a file's size and only download the initial kilobyte of the file?

When using Javascript/Node JS to download a file, you can check the file size and download only the first kilobyte of the file. This is useful if you want to hash the first kb and compare it with the hash of the complete file. If the hashes match and the ...

Disabling Babel in Nuxt.js: A Step-by-Step Guide

I've come to the decision to eliminate Babel transpilation from my projects, as I no longer see the need to accommodate pre-ES6 era browsers. However, my search efforts have yielded no results on how to go about this. My Nuxt project is currently fill ...

Struggling to implement Datatables row grouping using ajax is proving to be quite challenging

Is there a way to group rows in a table based on date ranges, using the data from the first column ("Due_Date"), and leveraging the rowGroup extension provided by Datatables? I've tried various solutions found online, such as using the data property ( ...

Create unique identifiers for the TD elements of Viz.js that will be displayed within the SVG elements

Below is the DOT code snippet in Viz.js that I am working with: digraph G { node [fontname = "font-awesome"]; 17 [id=17, shape="hexagon", label=<<TABLE BORDER="0"> <TR><TD>undefined</TD></TR> <TR><TD>[47-56]< ...

Is there a way to have one element automatically expand when another is selected?

I'm currently utilizing the date and time picker from . However, I need some assistance with the current setup. Currently, the date and time pickers are in separate input fields. In order to select a date, I have to click on the Date input field, and ...

The Javascript function is malfunctioning, unable to assign the 'onclick' property to null

Here's the code snippet I'm working with: var exit = document.getElementById("exit"); exit.onclick = function() { "use strict"; document.getElementById("fadedDiv").style.display = "none" ; }; However, when I check the console, it shows ...

Unable to isolate segments of a string

Looking for a way to extract two different IDs from the following string: SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9: using Javascript. The regular expression being used is : ^SPList\:(?:[0-9A-Za-z\-]+ ...

Searching an array for values that match another array and storing the indexes of the found values in a new array in [mongodb]

I am attempting to find a solution for searching an array field in each document of a Collection for specific elements that are contained in another array. The goal is to output the indexes of the found elements as an array. For instance: Let's cons ...

Comparison between Mobile Phone's innerWidth and innerHeight Versus Resolution

My test phone, the Galaxy S3 Mini, has a resolution of 800x480 according to its specs. Strangely, when I run the following code in my HTML game: window.innerWidth window.innerHeight The width appears as 533 and the height as 295. I recently discovered ...

Using a PHP variable within a JavaScript function to incorporate its value into a select field, ultimately generating a response using JavaScript

As I work on developing a shopping cart, I have successfully stored the total value of the items in the cart in a PHP variable named $total. I attempted to transfer this value into a JavaScript variable labeled Shipping fee. Subsequently, I created a form ...

Dynamic CSS Class Implementation with KnockoutJS

Greetings, I am seeking assistance as I am new to KnockoutJS. I am working with a class named green-bar that I need to activate when two particular states are true. Unfortunately, the solution I came up with below is not functioning correctly, and I'm ...

Developing a RESTful API with Discord.js integrated into Express

Currently, I am faced with the challenge of integrating the Discord.js library into an Express RESTful API. The main issue at hand is how to effectively share the client instance between multiple controllers. The asynchronous initialization process complic ...

There was an error: "TypeError: Unable to access the equipmentImage property of

Help needed! I am encountering a strange error while trying to upload an equipment image from postman as form data. The error states: Type Error; Cannot read property equipmentImage. I am using express-fileupload for the image upload process. Can someone ...

Ways to retrieve arrow information in JavaScript?

I'm currently retrieving tabular data in Arrow format from an API where the response content-type is application/vnd.apache.arrow.stream. Within my React code, I am attempting to parse this response. However, I'm uncertain if this approach is the ...

Looking to verify the validity of my email and phone number

Looking for some assistance in validating my email and telephone inputs for the contact form. The current code for email validation is incorrect, so I need help fixing it. It should be something like this: if(email.length == 0 || email.indexOf('@&apo ...

Having trouble with the base64 output in React image cropping?

I am having some difficulties cropping and uploading an image to the server. The API server requires the image in base64 format, but I am receiving it as a blob. Does anyone know of a workaround for this issue? Any help would be greatly appreciated! I&apos ...

`Unveil the hidden edges of the Google timeline chart`

Does anyone know how to remove the chart border from a Google timeline chart using this script? <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load ...

Select a dropdown menu option in Cypress by clicking on it only if it is checked

In this html code snippet, I have multiple elements within a dropdown menu. I am looking for a way to click on an item only if it is selected (has the class selected) or has a check mark in front of the name, as shown in this screenshot. How can I achieve ...

Tips for showing HTML content in an Angular UI grid

I've been attempting to showcase HTML within the grid by checking out this resource: Add html link in anyone of ng-grid However, my attempts led me to this code snippet: var app = angular.module('myApp', ['ngGrid']); ...

Bespoke HTML, CSS, JavaScript, and PHP website designs within the Wordpress platform

I am a beginner in the world of Wordpress, coming from a background of creating websites from scratch. Currently, I am working on a Wordpress template (Astra) and looking to create a custom page using HTML, CSS, JavaScript, and PHP from the ground up to ad ...