Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

divide array of objects to 4 arrays js

const array = [{idx: 1, count: 100}, {idx: 2, count: 200}, {idx: 3, count: 200}, {idx: 4, count: 100}]

const result = array.reduce((carry, item) => {
    if (!carry.array.length || carry.count + item.count > 500) {
        carry.array.push([item]);
        carry.count = item.count;
    } else {
         carry.array[carry.array.length - 1].push(item);
         carry.count += item.count;
    }
    
    return carry;
}, {array: [], count: 0}).array;

console.log(result);
 Run code snippet
Comment

PREVIOUS NEXT
Code Example
Javascript :: js trigger change event 
Javascript :: javascript string except last character 
Javascript :: try catch in javascript 
Javascript :: jetbrains font vscode 
Javascript :: how to use flatlist keyextractor 
Javascript :: how to pronounce allele 
Javascript :: stuck at "resolving packages" 
Javascript :: how to access variables from render() to outside of render() in class react component 
Javascript :: javascript text to speech 
Javascript :: javascript date to hours minutes seconds 
Javascript :: how to clamp a value 
Javascript :: ajax run function after page load 
Javascript :: js date is weekend 
Javascript :: how to print a number with commas as thousands separators in javascript 
Javascript :: add and remove checked jquery 
Javascript :: js array for in vs for of 
Javascript :: react js font awesome icon not rendering 
Javascript :: select element by data attribute 
Javascript :: convert hex to decimal javascript 
Javascript :: mutation observer js 
Javascript :: jquery confirm delete massege 
Javascript :: parse date do weekday 
Javascript :: js copy a div 
Javascript :: Firebase CLI v11.0.1 is incompatible with Node.js v14.17.6 Please upgrade Node.js to version = 14.18.0 
Javascript :: js save session 
Javascript :: javascript copy an object without reference 
Javascript :: fakepath js 
Javascript :: how to remove 000webhost watermark 2019 
Javascript :: random choice js array 
Javascript :: vscode jsx html autocomplete 
ADD CONTENT
Topic
Content
Source link
Name
1+9 =