Can you provide a way to directly calculate the total length of all arrays within an array of objects?

How can I find the total length of arrays in an array of objects based on a specific property?

var myArray = 
[{
    "a" : 1,
    "b" : another Array
},
{
    "c" : 2,
    "b" : another Array
}
.....
]

Is there a more efficient way to achieve this instead of using the following code snippet?

var lengthOfEachObject = myArray.map(function(Obj){

    if(Obj.b){
       return Obj.b.length;
    }
    else{
       return 0;
    } 
});
lengthofEachObject.reduce(function(x,y){
    return x+y;
})

Feel free to suggest solutions that involve the use of external libraries.

Answer №1

To find the total sum of an array using .reduce without relying on .map, you can iterate through the array just once. Additionally, instead of using traditional if statements to assign a default value for b.length, you can utilize destructing assignment.

Take a look at this example:

const arr = [{a: 1, b: [1, 2, 3, 4, 5] }, {c: 2, b: [1, 2, 3]}, {e: 3}],
total = arr.reduce((acc, {b={length:0}}) => acc + b.length, 0);

console.log(total);

Answer №2

If you want to calculate the total length of a specific property in an array, you can leverage lodash's _.sumBy():

var data = [{"x":1,"y":[1,2,3]},{"z":2,"y":[4,5,6,7,8]},{"z":2}]

var totalLength = _.sumBy(data, 'y.length')

console.log(totalLength)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Answer №3

To extract the length using a closure for the desired key and then mapping this value is a smart approach.

const
    getLength = key => ({ [key]: { length = 0 } = {} }) => length,
    sum = (x, y) => x + y,
    data = [{ name: 'John', numbers: [1, 2, 3] }, { name: 'Jane', numbers: [4, 5, 6, 7] }];
    
console.log(data.map(getLength('numbers')).reduce(sum));
console.log(data.map(getLength('name')).reduce(sum));

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

What is the purpose of utilizing "({ })" syntax in jQuery?

What is the purpose of using ({ }) in this context? Does it involve delegation? Can you explain the significance of utilizing this syntax? What elements are being encapsulated within it? For instance: $.ajaxSetup ({ // <-- HERE error: fError, ...

Clearing a textarea in jQuery that is populated with text

Having an interesting dilemma. I'm trying to clear a <textarea> and then replace it with new content. The functions in the JSFiddle will work perfectly fine if the textarea is left empty, but as soon as any text is manually typed into it, the me ...

"Despite the null date in Node.js, the validation for expiration dates less than Date.now() is still being enforced

I am currently working on implementing validation for evaluating the finish status. However, my validation is encountering a problem with the "null" value of expiresAt. It should indicate that the evaluation has been successfully completed. The issue lie ...

Prevent displaying page confirmation prompts when a user clicks on hyperlinks

One way to display a confirmation message when a user tries to leave the current page is by using this method: window.addEventListener("beforeunload", function (e) { var confirmationMessage = "Are you sure you want to leave?"; ...

The scrolltop animation does not appear to be functioning properly on iOS devices

I have implemented a JavaScript effect to increase the line-height of each list item on my website as you scroll. It works perfectly on my Macbook and Android Smartphone, but for some reason, it's not working on an iPhone. Can anyone provide a solutio ...

Older versions of Android, specifically Android 7 or lower, seem to encounter issues with Apis in React Native when utilizing axios. Fortunately, this problem doesn

For fetching the data, I utilized the 'axios' library. Surprisingly, it works flawlessly on newer Android devices (specifically Android 9 and 10). However, when it comes to older devices like Android 7 or earlier, a persistent Network Error occur ...

Unable to click, but can only be activated by touchstart or mousedown

Is it possible to bind a 'click' event to a paragraph? Here is the function I am using: $(document).on('touchstart mousedown',"p span.text", function(e) { console.log('I was clicked'); *more code here* }); When I ...

Struggling with implementing the group by feature in AngularJS?

Currently, I am trying to group a select-window by 2 different object arrays - subcategories and rootcategories. Each subcategory has a relation id that links to the rootcategory's id. My goal is to have the dropdown window group the subcategories bas ...

What is the difference between using || (or) and defining a variable in JavaScript?

Similar Inquiry: What is the meaning of the expression (x = x || y)? On numerous occasions, I have noticed variables being assigned in this manner var d = d || {} or var = var || [] This has raised a few questions in my mind What is the main pu ...

Why do developers opt for getServerSideProps() over a standard asynchronous function in their code?

Recently, I decided to experiment with the getServerSideProps() function. While I understand it must have its purpose, to me it seems similar in utility to a typical async function. Take for example my current task of retrieving user data using Prisma and ...

Transforming text elements into JSON format

My text contains a list of items formatted as follows: var text = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso ...

Experiencing the 'Rich Embed fields cannot be empty' error even though my code is functioning properly

My code is set up to log when someone edits a message on Discord. It captures the original message, the edited message, the channel, and more details. Everything seems to be working fine, but I keep encountering an error indicating that my RichEmbed fields ...

What is the reason for this Javascript regular expression only successfully matching two out of three identical strings when filtering?

To better illustrate my question, I would like to reference the following link: http://codepen.io/anon/pen/mRxOEP Here are three seemingly identical inputs from customers: <span class="customer_country" id="SW1">, Switzerland</span> <span ...

Exploring the Possibilities of WebAudio API through Asynchronous Events

Is there a way to trigger events after an oscillator finishes playing using the webaudio API? I am attempting to update my Vue component reactively to display data in the DOM while a note is being played. Here's a snippet of my code: <template> ...

Using Javascript to efficiently remove elements with AJAX

Currently, I am learning the basics of HTML and focusing on tasks such as login/logout functionality, creating users, and deleting users (only permitted when logged in as an admin). For updating a user password, I have utilized PUT, for creating a user ac ...

Denied from being displayed in a frame due to a violation of the Content Security Policy directive by a parent element

I'm in the process of developing a Salesforce app that is displayed within an iframe on a Salesforce page. I am using a node express server to render this page. In order to ensure security compliance, I want the app to only display within the Salesfor ...

Animating back with a jQuery if statement

Is there a way to implement an if statement that triggers an animation when the right image reaches +400px, and then animates back to -400px upon hovering over the image? $('#left img').mouseenter(function() { $('#right img').animate ...

JavaScript code to use Angular expressions in an HTML document

I am facing an issue with using Angular expressions inside JavaScript within an ng-repeat loop on my HTML page (note that the app and controller have been declared elsewhere): <div ng-repeat="eleRubrique in scopeComplet"> <script type="text ...

changing the value of a text input based on the selected option in a dropdown using ajax

I attempted to update the text input value with data from the database after selecting an option from the dropdown list. However, I encountered an issue where the data is not populating the text input field. <?php //Including the database configuration ...

receiving an undefined value from a remote JSON object in Node.js

I have been struggling to extract the specific contents of a JSON api without success. Despite my best efforts, the console always returns undefined. My goal is to retrieve and display only the Question object from the JSON data. After spending several h ...