The functionality of the Reduce function appears to be malfunctioning

Below is the function I'm utilizing to extract and create issue objects from all documents of type inspection:

function (doc) {
  if(doc.doctype === "inspection"){
    for(var i=0; i<doc.issues.length; i++) {
      emit(doc.issues[i].id, {id: doc.issues[i].id, status: doc.issues[i].status, date: doc.date});
    }
  }
}

I am using the id property of each issue as the key to filter the results later by issue. This functionality works correctly and yields 4 different states for the same issue with varying dates:

{"total_rows":4,"offset":0,"rows":[
{"id":"31cc62d44e1723f4e39757758101a79a","key":"31cc62d44e1723f4e397577581019612","value":
{"id":"31cc62d44e1723f4e397577581019612","status":"pending","date":"2015-09-02"}},
{"id":"31cc62d44e1723f4e39757758101f808","key":"31cc62d44e1723f4e397577581019612","value":    
{"id":"31cc62d44e1723f4e397577581019612","status":"pending","date":"2015-09-16"}},
{"id":"31cc62d44e1723f4e39757758102f70e","key":"31cc62d44e1723f4e397577581019612","value":    
{"id":"31cc62d44e1723f4e397577581019612","status":"pending","date":"2015-11-01"}},
{"id":"31cc62d44e1723f4e397577581033cab","key":"31cc62d44e1723f4e397577581019612","value":    
{"id":"31cc62d44e1723f4e397577581019612","status":"cancelled","date":"2015-12-07"}}
]}

The challenge arises when attempting to run a reduce function to fetch only the latest issue, not being able to iterate through all values. Even though the map function returns 4 rows, the length of the values parameter in the reduce function turns out to be 3 as shown below:

function (keys, values, rereduce) {
    return values.length
}

{"rows":[
{"key":null,"value":3}
]}

Furthermore, when trying to display the original values to understand the situation better, it is apparent that two of the values have been grouped together unexpectedly:

{"rows":[
{"key":null,"value":[    
[{"id":"31cc62d44e1723f4e397577581019612","status":"pending","date":"2015-11-01"},
{"id":"31cc62d44e1723f4e397577581019612","status":"pending","date":"2015-09-02"}],
[{"id":"31cc62d44e1723f4e397577581019612","status":"cancelled","date":"2015-12-07"}],
[{"id":"31cc62d44e1723f4e397577581019612","status":"pending","date":"2015-09-16"}]]}
]}

This demonstrates a case where the first two objects are combined into one array.

In this perplexing scenario, I seem to believe it's a simple task but I cannot pinpoint what might be amiss...

I attempted iterating through the values parameter to compare the date attribute, however, that did not yield successful results. Similarly, using the following code to recursively search for the id attribute also proved to be unsuccessful:

function (keys, values, rereduce) {
    var res = [];        
    function extractVal(obj) {
        if(obj.id) {
            res.push(obj.id);
        }else {
            for(key in obj) {
                extractVal(obj[key]);
            }
        }
    }

    extractVal(values);
    return res;
}

Answer №1

Alright, so after some investigation, here's what I've deduced. Please feel free to correct me if I'm mistaken.

The reduce function executes multiple times with the rereduce value set to false initially, and then makes a final run with rereduce set to true. If I simply return the values array in cases where rereduce is false, I will end up with an array containing those returned arrays as the values parameter during the last step when rereduce = true.

To extract the objects from the map function's return values, I'll need to implement a nested loop like this:

function (keys, values, rereduce) {
    var arr=[];
    if(rereduce){
        for(var i=0; i<values.length; i++) {
            for(var j=0; j<values[i].length; j++) {
                arr.push(values[i][j]);
            }
        }
        return arr;
    } else{
        return values;
    }
}

Lastly, instead of simply returning the arr parameter, I'll need to apply some processing to filter out the results that should actually be returned by the reduce function.

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

Guide to activating the timer specifically on select pages with jQuery Mobile

I've developed a quiz application using jQuery Mobile and I am working on implementing a timer feature. The timer should run from 0 seconds up to 1 hour but only when the user is viewing specific pages, specifically the question pages. The timer is di ...

Obtain element by selecting a specific class using Javascript

<select class="tmcp-field tillagg-width tm-epo-field tmcp-select" name="tmcp_select_30" data-price="" data-rules="" data-original-rules="" id="tmcp_select_ ...

What is the best way to conceal a callback form once it has been successfully submitted?

In my callback form, everything seems to be functioning properly. However, there is a slight issue when the client hits the submit button multiple times. Each time they do so, a notification saying "Your request sent successfully" pops up next to the butto ...

What is the best way to export JSON data in an array format instead of individual objects in Mapping Dataflow Datafactory?

https://i.sstatic.net/UFhMI.png I have been trying to export my transformed data from a mapping dataflow to a JSON file. However, the records are turning out as separate JSON objects instead of being enclosed in an array with commas between them as illust ...

What is the equivalent JavaScript/TypeScript function for this Python code snippet?

I'm having trouble converting this code snippet to JavaScript or TypeScript: def get_index(self): path = self.get_request_path() if "/_async_search" in path and "/_search": // If no index is found, u ...

Implement AJAX in order to circumvent fees from Google Maps and display maps exclusively upon user interaction by clicking a designated button

Starting July 16, 2018, the Google Maps API is no longer completely free. After July 16, 2018, in order to continue utilizing the Google Maps Platform APIs, you must activate billing for each of your projects. (https://developers.google.com/maps/documentat ...

Downloading files in AngularJS can sometimes be problematic when the file name contains spaces

I am currently using AngularJS to download files by sending GET requests. The file I am trying to download is named flower-red.jpg. Here is an example of my request: GET http://localhost:8080/aml/downloadDoc/852410507V/flower-red.jpg The download is succ ...

Duplicate the identical data retrieval query, this time utilizing a JavaScript Ajax post method

To enhance the data request query, implement a JavaScript Ajax post method to avoid page refresh when the button is pressed. This will allow for requesting another page and displaying it in a designated section on the webpage. Here's the code snippet ...

"Exploring the possibilities of ASP.NET and NoSQL integration

After delving into some NoSQL concepts and reading articles about MongoDB & CouchDB, it appears that they offer a greater opportunity to build scalable web applications. However, I need more clarity on whether they provide the same features as SQL Server ...

Tips for increasing the height of a ghost image for an HTML draggable element

I'm currently working on a scheduling calendar that allows users to book time slots and easily drag and drop them to adjust the time. Each time slot is represented as a draggable HTML element. However, I've noticed a problem where the preview ima ...

Displaying a JSON response in a jQuery alert box

{ user: [ { id: 476, customer: { id: "375", name: "test", avatar: null, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail=" ...

Issue with passing multiple promises to $q.all function

Currently, I am attempting to iterate through an object and fetch data for each iteration from two separate service API functions. These functions return promises due to using the $http object, which means I must wait for the responses before populating my ...

Is it necessary to specify the server-side script within the "routes" directory?

I'm currently developing a NodeJS Express application and from what I gather, the communication between the server and client is achieved by incorporating an AJAX script in a JavaScript file (on the client-side) and implementing a listener function (f ...

What is the reason for MongoDB throwing an error when an array of objects is treated as a string?

I'm finding myself quite puzzled by the error I'm encountering, as it appears to be very similar to me. When running a Mongoose Seed, the model structure looks like this: User Model const mongoose = require("mongoose") const Schema = mongoose. ...

Showing the output of an HTTP request in hapi.js version 17.2.0

I am attempting to showcase a page utilizing the latest version of HapiJS 17, which has a dependency on HTTP requests. Essentially, I am consuming a REST API and then returning it using the new response toolkit known as 'h toolkit,' but an error ...

Python JSON deep assertion techniques

Currently I am making an API call and the response coming from the server is in JSON format. Here's how the response looks: { "status": 0, "not_passed": 1, "why": [ { "code": 229, "reason": "some reason", } ] } I have tw ...

Tips for embedding variables in a string using VueJS

I'm looking for a way to interpolate a string in VueJS that includes variables and HTML. Is there a method in Vue that allows for this? component.vue <template> <div v-html="test1"></div> </template> <script> expo ...

Issue with modal dialog not triggering onshow event after postback

In my application, I have a Bootstrap modal dialog that is used to display data when the user clicks on "Edit" in a jQuery data table. The modal contains Cancel and Submit buttons. Everything works correctly when I open the modal, click Cancel, select ano ...

Loading data with Ajax from a remote file using a specific identifier

Can someone lend me a hand with an issue I'm facing? I've set up a small like system here. Within my HTML file, I have various data with unique IDs. Take a look at the code in my remote.html file below: <span id="14">314</span> < ...

Loop through an object in JQ only if it is present

The structure provided is as follows: { "hits": [ { "_index": "main" }, { "_index": "main", "accordions": [ { "id": "1", "accordionBod ...