Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript recursive on object of arrays

let company = {
  sales: [{name: 'John', salary: 1000}, {name: 'Alice', salary: 1600 }],
  development: {
    sites: [{name: 'Peter', salary: 2000}, {name: 'Alex', salary: 1800 }],
    internals: [{name: 'Jack', salary: 1300}]
  }
};

// The function to do the job
function sumSalaries(department) {
  if (Array.isArray(department)) { // case (1)
    return department.reduce((prev, current) => prev + current.salary, 0); // sum the array
  } else { // case (2)
    let sum = 0;
    for (let subdep of Object.values(department)) {
      sum += sumSalaries(subdep); // recursively call for subdepartments, sum the results
    }
    return sum;
  }
}

alert(sumSalaries(company)); // 7700
Comment

PREVIOUS NEXT
Code Example
Javascript :: batch mkdir 
Javascript :: discord.js reading json object from json 
Javascript :: vue file 
Javascript :: self-invoking function 
Javascript :: backdrop issue with multiple modal 
Javascript :: dropzone upload on one file 
Javascript :: lazy load npm package 
Javascript :: how to use yarn to create next app 
Javascript :: ckeditor ignore contenteditable 
Javascript :: javascript assign multiple variables to same value ES6 
Javascript :: javascript type checking 
Javascript :: look behind regex 
Javascript :: filepond remove file after upload 
Javascript :: react router hooks 
Javascript :: ejs 
Javascript :: jquery scroll to element toggle menu item 
Javascript :: Remove an item by index position 
Javascript :: jquery get label text only for input 
Javascript :: react this.state 
Javascript :: clock picker jquery 
Javascript :: sum array elements in javascript 
Javascript :: promise syntax in js 
Javascript :: response intersepters for axios create 
Javascript :: create array of numbers javascript 
Javascript :: where to initialize state in react 
Javascript :: react js and graphql integration 
Javascript :: splice remove 0 elements before index and insert new element 
Javascript :: javascript xpath 
Javascript :: delete in array 
Javascript :: update state in useState hook 
ADD CONTENT
Topic
Content
Source link
Name
9+7 =