Looping over an array in lo-dash and calculating a total based on a specific condition

I have a dataset that has been simplified:

var data = [{
    size: 400
}, {
    size: 500
}, {
    size: 800
}, {
    size: 400
}, {
    size: 400
} {
    size: 300
}, {
    size: 300
}, {
    size: 800
}];
var windowWidth = 800;

How can I use lodash to create a new array based on how many sizes would fit into the window width. The desired final dataset will be structured like this

var newArray = [{
            group: [0],
            size: 400
        }, {
            group: [1],
            size: 500
        }, {
            group: [2],
            size: 800
        }, {
            group: [3, 4],
            size: 800
        }, {
            group: [5,6],
            size: 600
        }, {

            group: [7],
            size: 800,
        }

The key group represents the indexes of data[n] where the size is less than the window width. The key size shows the accumulated size of the group.

Note: data[n] increments and does not loop back to data[0] indefinitely.

Does data[n] fit inside the window? If yes, push to group; move to data[n + 1].size; check condition again

If no, create a new group(); go to data[n + 1].size; check condition

Answer №1

const total = _.chain(data).pluck('length').reduce(function(sum, value, index) {    
    if (_.isEmpty(sum) || value + _.last(sum).length > windowWidth)
        sum.push({ length: value, groups: [index] });
    else
    {
        const lastItem = _.last(sum);
        lastItem.length += value;
        lastItem.groups = lastItem.groups || [];
        lastItem.groups.push(index);
    }
    return sum;
}, []).value();

http://jsfiddle.net/123abcde/

Answer №2

It appears that I have identified the solution to your problem:

const dataList = [{size: 400}, {size: 500}, {size: 800}, {size: 400}, {size: 400}, {size: 300}, {size: 300}, {size: 800}],
    newArray = [],
    previousSize = 0,
    lastIndex,
    windowWidth = 800;
for(let index = 0; index < dataList.length; index++){
    lastIndex = newArray.length - 1;
    if(previousSize == dataList[index].size && (newArray[lastIndex].size + dataList[index].size < windowWidth)){
        newArray[lastIndex].group.push(index);
        newArray[lastIndex].size += dataList[index].size;
    }else{
        previousSize = dataList[index].size;
        newArray.push({group:[index], size: dataList[index].size});
    }
}

console.log(newArray);
alert(JSON.stringify(newArray));

Answer №3

Uncertain of the optimal method, but this solution exclusively utilizes lodash functions:

var indexed = _.map(data, function (e, i) {
  e['index'] = i;
  return e
});
var grouped = _.groupBy(indexed, function (e) {
  return e.size
});
var newArray = _.map(grouped, function (e, key) {
  return {'size': key, 'group': _.pluck(e, 'index')}
});

Version 2

A more streamlined alternative incorporating _.reduce for the grouping and _.map for converting the grouped object into a list of objects. Eliminates all sizes exceeding windowWidth.

var windowWidth = 400;
var grouped = _.reduce(data, function (result, e, i) {
  if (e.size <= windowWidth) {
    var group = result[e.size];
    if (!group) {
      group = result[e.size] = [];
    }
    group.push(i)
  }
  return result;
}, {});
var newArray = _.map(grouped, function (e, key) {
  return {'size': key, 'group': e}
});

View Demo

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

Having trouble with my NodeJS POST route implementation with Axios

I encountered an issue with my Post route using axios. Upon clicking the button to create a new user, I received the following error message: (node:13901) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'username' of undefined ...

Sending multiple PHP arrays as part of an AJAX response

I have been attempting to send multiple arrays in an Ajax request response (get), but have been struggling to achieve it. Here is the PHP code I want to include in the Ajax request response: echo json_encode($catdata); echo json_encode($productdata); ech ...

A step-by-step guide to extracting serialized data and displaying it in a table using unserialization in

Hello there, I go by the name of Tri. Currently, I am trying to store serialized data into a MySQL database using PHP. However, I am facing an issue with retrieving this data and displaying it in a table after unserialization. After unserializing the da ...

Enhancing the efficiency of a Puppeteer web scraping operation

app.get("/home", async (req, res) => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); const pageNumber = req.query.page || 1; await page.goto(`https://gogoanimehd.io/?page=${pageNumber ...

Leveraging javascript to extract data from several input fields and dynamically incorporate them into a table

I'm currently in the process of developing a script that extracts field values and organizes them into a table for verification purposes. The challenge I face is that users have the ability to add multiple fields (up to 5), each with its own unique id ...

A similar functionality to the async pipe in TypeScript

In my Ionic2 project, I'm utilizing ng-translate from ng2-translate to translate strings in the code. Currently, I am using the service in the following way: translate.get('ERROR').subscribe((res: string) => { //The translated string ...

What discrepancies exist between running npm install on Windows versus Linux operating systems?

Just have a quick question to ask. I've been searching online with no luck. If I were to run npm install on a Windows machine to set up my dependencies, would it be viable to transfer the node_modules directory to a Linux machine and execute my nodej ...

Each div in prevAlll() will have its own unique CSS background

In continuation of my initial query, which has now been resolved, you can find the original question here. JS: $(function() { var scaletext = { 1: 'SA', 2: 'A', 3: 'N', 4: 'Da', 5: 'SDa' } $(&a ...

Can the lexical scope of a function in JS be maintained while overriding it?

When faced with the task of modifying a function provided by a third-party module, I considered simply copying the function and making changes to it. However, the issue lies in the fact that this function relies on other functions and variables within its ...

How can I use Angular 6 to design an interactive user interface with drag-and-drop functionality?

I am looking to make a dynamic form using Angular 7 with drag and drop functionality. The controls I need for building the form are: Check Boxes Multiple Headings Sub Headings Table + Formatted Tables + Unformulated Checkbox + text Text Fields + formatte ...

AngularJS directive: handling child elements

Is there a way to structure the directive below in order to have access to all the ul elements within the link function? In the code snippet provided, when examining the elm (logged in console), it appears as a comment type and ul are displayed as sibling ...

Utilizing a comparator while handling abstract classes: Tips and Tricks

I have been experimenting with using the compareTo method and implementing the Comparable interface, but I am struggling to find a way to compare two objects and return an integer (-1 if the first object is smaller than the second one, 0 if they are equal, ...

AngularJS object array function parameter is not defined

Recently, I've been honing my AngularJS1x skills by following tutorials on Lynda and Udemy. One tutorial involved creating a multiple choice quiz. To test my understanding, I decided to modify the code and transform it into a fill-in-the-blank quiz. ...

Modify the key within an array of objects that share a common key

I have an object structured as follows: NewObjName: Object { OLDCOLUMNNAME1: "NEWCOLUMN_NAME1", OLDCOLUMNNAME2: "NEWCOLUMN_NAME2", OLDCOLUMNNAME3: "NEWCOLUMN_NAME3"} Next, there is an array containing objects in this format: ...

Modifying the date in the Bootstrap Date Range Picker does not trigger the changed event

Here is the code where I am trying to update the selected date from Bootstrap date range picker in the "from" and "to" variables that are used in the "cashadvance" query. I believe there might be an issue in the date Range Picker callback function. In th ...

Maintain the execution of a Node.js function without reliance on any front-end calls

Looking to continuously generate random data in MongoDB using my NodeJS API without making calls from the client-side. var autoCreate = function(){ var randomNumb = (Math.random()* (10-0) + 0).toFixed(0); var randomThing = randomstring.generate({ ...

Is your console showing an error message about an incompatible IE Document Mode?

I am encountering an issue with the following code in my jsp page. <!--[if lt IE 7]><html lang="en" class="no-js lt-ie10 lt-ie9 lt-ie8 lt-ie7" xml:lang="en" xmlns:fb="http://www.facebook.com/2008/fbml"> <![endif]--> <!--[if IE 7]>& ...

Modify div content based on user selection

I have a question about updating the content of a div based on certain conditions in my code. Here is what I'm trying to achieve: <div class="form-control" ns-show="runningImport" disabled="disabled"> {{input[row.header_safe]}}{{select[row. ...

Django RGBField cannot locate jQuery

Working on a project that utilizes an RGBField, the following script is injected into the template (nested deep within django's structure, as its exact location remains elusive): <script type="text/javascript"> (function($){ ...

Navigate through set of Mongoose information

I have a challenge where I need to retrieve an array of data from Mongoose, iterate through the array, and add an object to my Three.js scene for each item in the array. However, when I try to render the scene in the browser, I encounter an error that say ...