Calculating the number of attributes across various elements within an array

Can someone assist me with counting elements in a multi-object array?

//constructor function
function Bookdes(title, author, pages, current_page, available){
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.current_page = current_page;
    this.available = available;
}
//array of books
var bookarrays = [
    new Bookdes("Fast Cars", "John Burns", 205, 43, "true"),
    new Bookdes("Slow Cars", "Joe Fast", 70, 32, "false" ),
    new Bookdes("Big Cars", "Darla Jean", 234, 42, "true"),
    new Bookdes("Small Cars", "Dema Jones", 214, 34, "false"),
    new Bookdes("Cars", "Alex Best", 235, 41, "true")
];

I am now looking to count the number of books that are available (true), calculate the sum of pages read (current_page), and determine the length of the longest title. Any suggestions on how I can achieve this?

Thank you!

Answer №1

When delving into functional programming techniques, the initial intimidation often gives way to simplicity when solving problems like this. Utilizing libraries such as Ramda (full disclosure: I am one of the authors; however, these techniques are available in various other functional programming libraries), tasks can be achieved effortlessly:

var countAvailable = R.pipe(R.filter(R.propEq('available', 'true')), R.prop('length'));
var pagesRead = R.pipe(R.pluck('current_page'), R.sum);
var maxTitleLength = R.pipe(R.pluck('title'), R.pluck('length'), R.max);

Each function provided here can be called with the data from bookarrays. The functionality is demonstrated on the Ramda REPL.

The key takeaway is that common functions like pluck offer the ability to transform lists into simpler forms for further manipulation. For example,

pluck('title')(bookarrays);
//=> ["Fast Cars", "Slow Cars", "Big Cars", "Small Cars", "Cars"]

This highlights how using functions like pluck, max, and pipe allows for the creation of easily accessible functions like maxTitleLength. Functional programming emphasizes the development of simple, composable functions that operate on the same data structures, such as lists.


Update

This approach isn't solely about the library itself but rather focuses on creating multiple small, reusable, composable components to construct more intricate functions. Below is a curated selection of functions designed to address these specific issues:

var add = function(a, b) {
  return a + b;
};

var sum = function(list) {
  return list.reduce(add, 0);
};

var max = function(list) {
  return Math.max.apply(Math, list);
};

var map = function(fn) {
  return function(list) {
    return list.map(fn);
  };
};

var prop = function(name) {
  return function(obj) {
    return obj[name];
  };
};

var pipe = function() {
    var funcs = arguments;
    return function() {
        var args = arguments;
        for (var i = 0; i < funcs.length; i++) {
            args = [funcs[i].apply(this, args)];
        }
        return args[0];
    };
};

var pluck = pipe(prop, map);

var filter = function(fn) {
  return function(list) {
    return list.filter(fn);
  };
};

var propEq = function(name, val) {
  return function(obj) {
    return obj[name] === val;
  };
}

To utilize this utility library, combine these functions in your code. Notice the straightforward definition of pluck.

You could also simplify it by writing:

var pluck = function(name) {
  return map(prop(name));
};

However, leveraging pipe for combining functions makes it easier:

var pluck = pipe(prop, map);

Although not the most direct method for completing this task, having these versatile functions readily available will streamline future processes. This essence captures the crux of functional programming.


This discussion excludes one crucial tool in functional programming known as currying. An insightful article by Hugh Jackson explores its benefits (link here), while I have elaborated on it in another piece (additional details here). Currying would enhance the simplicity of these functions significantly. For instance, instead of

var propEq = function(name, val) {
  return function(obj) {
    return obj[name] === val;
  };
}

We could achieve the same result with:

var propEq = curry(function(name, val, obj) {
  return obj[name] === val;
});

This alteration paves the way for a cleaner and more flexible approach. Embracing a curry function would not only refine the existing code but also enhance its versatility.

Answer №2

Click Here for Live Demo

// Defining a constructor function for books
function BookDescription(title, author, pages, current_page, available){
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.current_page = current_page;
    this.available = available === 'true';
}
// Creating an array of book objects
var bookArray = [
    new BookDescription("Fast Cars", "John Burns", 205, 43, "true"),
    new BookDescription("Slow Cars", "Joe Fast", 70, 32, "false" ),
    new BookDescription("Big Cars", "Darla Jean", 234, 42, "true"),
    new BookDescription("Small Cars", "Dema Jones", 214, 34, "false"),
    new BookDescription("Cars", "Alex Best", 235, 41, "true")
];

var availableBooks = 0;
var totalPages = 0;
var longestTitle = '';

for (var i = 0; i < bookArray.length; i++) {
    bookArray[i].available && (availableBooks += 1);
    totalPages += bookArray[i].current_page;
    longestTitle = bookArray[i].title.length > longestTitle.length ? bookArray[i].title : longestTitle;
}

alert(availableBooks);
alert(totalPages);
alert(longestTitle);

Answer №3

Take a look at this interactive demo

//constructor function
function Bookdes(title, author, pages, current_page, available){
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.current_page = current_page;
    this.available = available;
}
//array of books
var bookarrays = [
    new Bookdes("Fast Cars", "John Burns", 205, 43, "true"),
    new Bookdes("Slow Cars", "Joe Fast", 70, 32, "false" ),
    new Bookdes("Big Cars", "Darla Jean", 234, 42, "true"),
    new Bookdes("Small Cars", "Dema Jones", 214, 34, "false"),
    new Bookdes("Cars", "Alex Best", 235, 41, "true")
];

function sum(){
   var i;
    var count = 0;
    var maxlen = 0;
    var read = 0;
    for(i=0; i<bookarrays.length; i++){
        if(bookarrays[i].title.length > maxlen){
             maxlen = bookarrays[i].title.length;
        }
        if(bookarrays[i].available === "true" || bookarrays[i].available === true){
             count++;   
        }
        read += bookarrays[i].current_page;

    }
    $("#out").html("Count: " + count + "<br>Maxlength: " + maxlen + "<br>read: " + read);
}

$(function(){
       sum();
});

Here is some basic HTML:

<div id="out"></div>

The output will be:

Count: 3
Maxlength: 10
read: 192

You can iterate through each element and customize as needed

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

Three.js fails to load due to Require.js issue

Having encountered a JavaScript error in browser (on the last line mentioned above) with generated code from TypeScript: define(["require", "exports", "three", "jquery", "./test"], function (require, exports, THREE, jQuery, Test) { var Main = (function () ...

Refresh client web pages with JSON data without using eval

I am currently working as a consultant on a web application that functions as a single page app. The main purpose of the app is to constantly fetch new json data in the background (approximately every minute) and then display it on the screen. Our clients ...

The functionality of "Priority Nav" is compromised when a div is floated

I am currently utilizing the "Priority Navigation" design technique. This means that when the viewport width is reduced and there isn't enough space for all the list-items to fit horizontally, they are moved into another nested list under a "more" lin ...

Combining arrays of objects sharing a common key yet varying in structure

Currently, I am facing a challenge while working on this problem using Typescript. It has been quite some time since I started working on it and I am hoping that the helpful community at StackOverflow could provide assistance :) The scenario involves two ...

Tips for displaying two input decorations in Material UI beside one another within a text field

In the Text Field demonstration, I noticed input adornments at the start and end. However, I am looking to have two input adornments at the end specifically. I attempted to add them using endAdornment: {InputAdornment InputAdornment}, but encountered an er ...

Guide to uploading a recorded audio file (Blob) to a server using ReactJS

I'm having trouble using the react-media-recorder library to send recorded voice as a file to my backend. The backend only supports mp3 and ogg formats. Can anyone provide guidance on how to accomplish this task? Your help would be greatly appreciated ...

The text link on an iOS device is trapped by a persistent blue border

I've encountered an issue on my iOS device. When I open the menu with a popup, there is a blue border around the text element, even though it's not a hyperlink underline. https://i.sstatic.net/WA3rz.jpg I attempted to resolve this using the fol ...

Redirecting using JavaScript with headers

Allow me to clarify the situation, In my login.php file, I have the following code: if(isset($_SESSION['user'])!="") { header("Location: home.php"); } This code ensures that if a user successfully logs in, the URL will always show mysite.com/h ...

Error encountered in React Native packager due to naming conflict between "lodash" and "yeoman-generator" libraries

Issue Description Within my current project, I am utilizing "react-native": "0.36.0" along with the following dependencies: "lodash": "^4.15.0" "yeoman-generator": "^0.24.1" Upon using versions above "^3.10.1" for "lodash" and "0.21.2" for "yeoman-gene ...

Trouble displaying events from resource in Angular UI calendar integration

I have encountered a perplexing issue with Angular UI Calendar. My goal is to fetch events from an API and display them on the calendar. Initially, the events load correctly when the page is first loaded. However, if I navigate to the next month and then r ...

Is there a way to load an image onto the ngx-image-cropper without triggering the imageChangedEvent event?

My latest project involved creating a custom cropper using ngx-image-cropper, which allows for cropping and rotating images. For the sprint demo, I needed the images to be displayed as soon as the application loads without having to trigger the fileChangeE ...

What is the proper way to initialize objects in an array that has been dynamically generated?

class bishop:unit {} class knight:unit {} class peasant:unit {} void Battle(unit first, unit second, byte firstAmount, byte secondAmount) { System.Array sideA = System.Array.CreateInstance(first.GetType(),firstAmount); for(int i=0; i< firstAmount; ...

Encountering issues with the phaser framework while setting up a server on xampp, faced with errors in javascript and html

Recently, I've been working on a game using Phaser and encountered some issues while trying to run the code in XAMPP. The game's base is located at htdocs/itw/test.html, with the necessary pngs and json file stored in htdocs/itw/assets/. The pngs ...

Can the identical script be implemented by utilizing two separate JavaScript files?

My knowledge of JavaScript is limited, so I often rely on resources like JavaScript.com and Dynamic Drive for coding. Recently, I came across some scripts that reference two different .js files. <script type="text/javascript" src="lib/prototype.js"> ...

What's the best way to use the like query in Mongoose?

Struggling with applying a Like query using Mongoose in the MEAN stack. Despite trying various solutions found online, nothing seems to work for me. Here is the model schema: const mongoose = require('mongoose'); const ItemTransactionSchema = ...

The function array.map() is not functioning as anticipated when trying to display the <li> element within a React component

I'm having trouble rendering multiple <li> components using the map() function. No content is being displayed on the screen and I'm not receiving any error messages, so I'm unsure of what the issue might be. reviewCard = revie ...

What is the method to launch a YouTube embedded video in a new tab?

I have a YouTube video embedded on my website. I've been trying to figure out how to open it in a new tab, but haven't been successful. Can someone help me with this issue? Here is the code I'm using: <a href="https://www.youtube.com/ ...

Remove several elements from an array within the state of a React component using values from a second array

Here is an array let removed = [ {id: '123', name: 'Something'}, {id: '321', name: 'Something1'} ]; and I also have this piece of code this.setState({ config: { ...this.state.config, ...

Unable to reach the form within the AngularJS controller

Having trouble accessing a form variable from my controller. When I try to access it using $scope.locationForm, it returns 'undefined'. However, when I use console.log($scope), I can see the locationForm in the console. Here is my HTML code: &l ...

Merge an object depending on the matching criteria

Welcome fellow programmers and like-minded individuals, Every time a user clicks on a basket to add a product, an object named field_x is created, where x increments by 1 starting from 1. My objective is to develop a function that can identify duplicate ...