Utilizing underscore.js to aggregate data points: A comprehensive guide

If I have an array containing 6 numeric data points and I want to transform it into a new array with only 3 data points, where each point is the sum of two of the original points.

For example: [1,1,1,1,1,1] would become [2,2,2]

What would be the most efficient method to achieve this using a library such as underscore.js?

Answer №1

If one were inclined to approach this task in a more generic and functional manner, they might consider the following:

function allowIndices(idx) {
    return function(item, index) {
        return index % idx;
    }
}

function calculateSum() {
    return _.reduce(_.toArray(arguments)[0], function(result, current) {
        return result + current;
    }, 0);
}

var isIndexOdd = allowIndices(2);

var zippedData = _.zip(_.reject(data, isIndexOdd), _.filter(data, isIndexOdd));
console.log(_.map(zippedData, calculateSum));
# [ 3, 7, 11 ]

However, it should be noted that while this approach is certainly valid, it may not offer the same level of performance as the more traditional method shown below:

var results = [];
for (var i = 0; i < data.length; i += 2) {
    results.push(data[i] + data[i + 1]);
}
console.log(results);

Answer №2

After much exploration, I have come across a possible solution. However, I am open to better ideas.

    array = [1,1,1,1,1,1];
    period = 2;
    var result = [];
    _.inject( array, function ( total, value, index) {
        if ((index + 1) % period === 0) {
            result.push(total + value);
            return 0;
        } else {
            return total + value
        }
    }, 0);

Answer №3

One way to achieve this using lodash is shown below:

const numbersArray = _.fill(Array(6), 1);
const reducerFunction = (sum, number) => sum += number;
const chunkedArray = _.chain(numbersArray).chunk(2).map(subArray => subArray.reduce(reducerFunction)).value();

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

Facing issues with Handsontable opening within a jQuery UI dialog?

After implementing the Handsontable plugin in multiple tables, everything appears as expected on the parent page. However, when attempting to open a dialog containing a table, the tables do not display properly (only in IE). A demonstration of this issue c ...

Display div - conceal div - pause for 15 minutes - continue the cycle

I have a challenging JavaScript task that I've been struggling with for quite some time. The goal is to display a div for 5 seconds, hide it, wait for 15 minutes, then show it again for another 5 seconds, and continue this process in an infinite loop. ...

What methods can be used to search within one array in order to filter another array contained in a list?

Looking for suggestions on creating a filter in one list based on another list How can I handle filtering an array within a list by searching in another array? For example... myArray = [ { "name": "Item-A", "tags": ["Facebook" ...

Using Ajax without implementing JavaScript

Is it possible to develop an application that utilizes Ajax without relying on JavaScript, allowing it to function even if JavaScript is disabled by the user in their browser? Are there any restrictions or limitations to consider? ...

What is the best way to include a background image in a div within a React component?

I'm currently following a tutorial on creating an RPG game using React. The tutorial can be found at this link. I am trying to replicate the presenter's code by typing it out myself. However, I'm running into an issue when attempting to add ...

Hide a specific page's Vue component button within a table

I have a component that displays a table on various pages. Within this table, there is a button to create goals. However, I want to control when this button appears on certain pages and exclude it from others. Below is the code for the table component and ...

Getting the ID of a select input option in Vue.js using FormulateInput

Recently, I've been working with a FormulateInput select component that looks like this: <FormulateInput name="broj_zns-a" @change="setZns" :value="brojZnsa" type="select" label="Broj ZNS- ...

Manage the dimensions of elements using Javascript on the client side

Here is a form I created: <form action="#" enctype="multipart/form-data" method="post" name="..." id="formPhoto" class="fmp"> <input type="file" name="pho" id="photo" class="inph" accept="image/*"> <button type="submit" id=" ...

Adjusting the sensitivity of mousewheel and trackpad using JavaScript

I am currently utilizing CSS3 to smoothly move a div up and down based on the direction of scrolling. By monitoring the mouse wheel event, I can detect when a user scrolls down and trigger a CSS3 transition to slide the div up. However, I am encountering a ...

Google Chrome is unable to process Jquery JSON .each() function

My website has a simple chat application that is functioning well. It uses ajax to request data in this manner: $.ajax({ url: "fetch/"+CHAT_SESSION_ID+"/"+LAST_MESSAGE_ID, dataType: "json", cache: false, success: function(data) { if (data.session_ac ...

Function that is triggered repeatedly when modifying the state within it

Within my render method, I am calling a handlePageClick function like this: onPageChange={this.handlePageClick} The function itself looks like this: handlePageClick = data => { this.setState({ circleloading: true }); let names = ...

The parsing of a date string in JavaScript is done with the timezone of

let userInputDate = "2019-05-26" // received from browser query e.g. "d=1&date=2019-05-26" let parsedDate = new Date(userInputDate) console.log(JSON.stringify(parsedDate)) output: #=> "2019-05-25T19:00:00.0000Z" Issue When the user's time ...

Iterating over an array of lists to tally the elements

I've been struggling to count the number of objects in an array using JavaScript. Below is the array I'm trying to work with: <script> var arr = [ {"gateways":["ccu1"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_cam", ...

Reorganizing JSON Information

Currently, I am dealing with a JSON file that contains multiple sets of data structured like this: {"name": ["Adelphi University"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ...

leveraging insertAdjacentHTML within a React Component

I've been working on a project to replicate the Github contribution grid using React. My approach involves using insertAdjacentHTML to fill the grid container with several divs that I can then customize with styles. Unfortunately, I'm encounter ...

What causes the Next 13 App to reload when the route is changed?

I am currently working on the Next 13 Application and facing an issue where clicking on navigation links from the sidebar changes the route, but unfortunately, the application is getting reloaded. It should ideally replace the component directly without re ...

Navigate audio tracks with JavaScript

I'm currently facing an issue with using a button to switch between two audio tracks being played in the browser. The method I have implemented switches to the second track, but it doesn't change the audio that is played afterward - instead, it s ...

Tips for preventing flex items from having equal height when collapsing

When I try to place elements from an array in a list with display flex, the height of other elements gets modified when one is collapsed. I have attempted different display and inline placement on li elements but nothing has worked so far. Is there a way ...

The image slider script I've built is functioning perfectly in Codepen, but unfortunately, it's not working as

My image slider called Orbit is functioning properly on Codepen.io, however when I try to run the exact same code on Plunker, it doesn't work at all. <ul class="slider" data-orbit> <li> <img src="http://foundation.zurb.com/docs/a ...

What is the process for making an Ajax request in Rails?

I'm attempting to send a variable through jQuery using the POST method, saving it in a controller, and then utilizing that same variable in Rails HTML to query a table. It seems like the variable isn't being passed to the controller. jQuery: v ...