Determine the total value of a specific key within a collection of objects

I am grappling with an array of objects:

let fileArray = [
  { filename: 'File1.txt', bytes: 12345, created: 1548360783511.728 },
  { filename: 'File2.txt', bytes: 34567, created: 1548361491237.182 },
  { filename: 'File3.txt', bytes: 23456, created: 1548361875763.893 },
  { filename: 'File4.txt', bytes: 56789, created: 1548360658932.682 }
];

I have two main objectives for this array: calculating the total bytes of all files in this array sum of numbers and identifying the file created first (smallest) Obtain smallest value from array in Javascript?.

I have considered using array.reduce(), however, it seems to be more suitable for flat arrays. Can it be used on specific keys of an array of objects, or would I need to create a temporary array containing all values for that key in the current array and then use array.reduce() on those values?

Answer №1

Below is a demonstration of using the reduce() method to perform specific operations on an array. Two custom methods are defined to reduce the array: one for calculating the sum of bytes and another for finding the minimum created value. Finally, the array is reduced by invoking the respective custom reduce methods.

let fileArray = [
  {filename: 'File1.txt', bytes: 12345, created: 1548360783511.728},
  {filename: 'File2.txt', bytes: 34567, created: 1548361491237.182},
  {filename: 'File3.txt', bytes: 23456, created: 1548361875763.893},
  {filename: 'File4.txt', bytes: 56789, created: 1548360658932.682}
];

// Custom reduce method for calculating the sum of bytes.

const reduceWithSumBytes = (res, {bytes}) => res += bytes;

// Custom reduce method for finding the minimum created value.

const reduceWithMinCreated = (res, {created}) =>
{
    return res && (created < res ? created : res) || created;
};

// Perform reduce() operation using the custom methods.

console.log(fileArray.reduce(reduceWithSumBytes, 0));
console.log(fileArray.reduce(reduceWithMinCreated, null));

Answer №2

Is this the traditional approach?

let totalSize = 0;
for(let index = 0; index < fileList.length; index++){
    totalSize += fileList[index].size;
}
console.log(totalSize);

Additionally,

let indexOfFirstFile = 0;
for(let index = 0; index < fileList.length; index++){
    if(fileList[index].created < fileList[indexOfFirstFile].created){
        indexOfFirstFile = index;
    }
}   
console.log(fileList[indexOfFirstFile].filename);

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

Leveraging ThemeProvider Parameters with Global Styled-Components

When working with styled-components, how can I access the props of the ThemeProvider in the context of global.js? For instance, in my theme.js file, I have ${props => props.theme.fonts.fontSize} set to a default font size of 16px. const theme = { ...

Tips on creating an onclick function in javaScript and linking it to innerHTML

let a = 10; let b = 15; document.getElementById("text").innerHTML = '<div onclick=\'testing("'a + '","' + b + '") > text </div>'; Welcome, I am new to this ...

Heroku NodeJS - Page Not Found: Error 404

I recently set up a Heroku server with BootBot running on it, but I'm facing challenges while trying to render an HTML page from it. Here is what I have in my code: var app = express(); var path = require('path'); app.use(express.static(pat ...

Customer is unable to locate the "InitializeAuthenticationService" function

After launching my application, the browser console keeps showing me three errors that all say Could not find 'AuthenticationService.init' ('AuthenticationService' was undefined). and Microsoft.JSInterop.JSException: Could not find &apo ...

Step-by-step guide on incorporating play/pause buttons for two distinct Bootstrap 5 carousels

I have been struggling to incorporate carousel controls on my website. I have tried looking at various examples on different platforms, like Stack Overflow, but I am only able to get one set of controls to work at a time. Here is my current setup: ...

Creating a list that renders responsively using ReactJS

I'm currently working on implementing a responsive search bar that filters through a list of pure components (up to 100 components displayed at once). However, I've noticed there is a slight half-second delay between typing the first letter and s ...

Switching from Vue's Options API to Composition API is like transforming your code from

My goal is to transition the code below from using the options API to the composition API in Vue while utilizing Typescript. data() { return { items: [ 'Car', 'Truck', 'Bike', 'Ca ...

When attempting to compile at runtime without an instance, the act of creating a function constructor can lead to an

My website is designed to function as a simple quiz game. It retrieves an array of JSON questions using AJAX, and for each question in the array, it displays the question itself along with buttons containing various options that were stored in the question ...

Utilize Parse cloud code to navigate and interact with object relationships

I am currently in the process of developing a Parse cloud code function that will produce a similar outcome to a GET request on parse/classes/MyClass, but with the IDs of the relations included. While I have successfully implemented this for a single obje ...

JavaScript file encountering a Typescript issue with a property defined in a subclass

Currently, I am utilizing Typescript to validate my Javascript files. One issue I have encountered is that when I inherit from a class, Typescript does not recognize the types of the properties in the parent class. I am unsure if I am overlooking something ...

React app's setTimeout function fails to execute at the designated time specified

I have a function set up in my React app to handle user authentication and signup. The function is supposed to display an alert message saying "Account Created" upon successful signup, and then redirect the user to their profile page after a 1-second delay ...

The alert box fails to display in the correct orientation when the condition is activated

Currently, I am working on implementing a sign-up feature using PHP. My main goal is to successfully store the user-entered data in MySQL database while ensuring that no duplicate usernames are allowed during account creation. Although everything is functi ...

Monitoring Website Load Speed using Performance API

After attending a recent talk by Steve Souders, I was fascinated by the discussion of the new performance spec being implemented by modern browsers. During his presentation, he used an example to demonstrate how to measure perceived page load time: var ti ...

Is there a way for redux-saga to pause until both actions occur at least once, regardless of the order in which they happen?

Just diving into Redux saga. I'm working on creating a saga that will fetch the initial state for the redux store from our API server. This task involves utilizing two asynchronous sagas: getCurrentUser and getGroups. The goal is to send these ajax ...

Angular alert: The configuration object used to initialize Webpack does not conform to the API schema

Recently encountered an error with angular 7 that started popping up today. Unsure of what's causing it. Attempted to update, remove, and reinstall all packages but still unable to resolve the issue. Error: Invalid configuration object. Webpack ini ...

Output values in JSON array are not displaying

I've been struggling with my code and have searched extensively for solutions to no avail. The issue I'm facing is that the output is completely blank, despite double and triple-checking all the necessary variables like host, user, pass, dbname, ...

Creating a secure ZIP file with password protection using node.js

Currently, I am faced with the challenge of creating a ZIP file in node.js with password protection. Despite using the "node-zip" module for this task, it lacks the functionality to provide password protection: var zip = new require('node-zip') ...

Determine the output by applying a constant value to the input

I'm having an issue with a loop function. The goal of the code is to allow users to enter a quantity of goods they want to buy, and then JavaScript calculates a fixed value based on the chosen quantity, which should be printed out. This functionality ...

Guide on resolving a "res is not defined" issue in Node.js

I've been struggling to test the controller logic for a user validation module, but I keep encountering an error that says "res is not defined" even after trying to define it. How can I properly define it so that it runs through the condition statemen ...

What is the best way to transfer an ID to a dropdown selection list?

Whenever a user chooses an option from a drop-down menu, an event needs to be triggered. I have a checkbox that retrieves an ID from the database; based on this ID, a user can be added or removed from the drop-down menu. var ajReq = new XMLHttpRequest(); ...