Unable to shrink array within an object

I'm encountering an issue while trying to reduce an array within an object. The error message I receive is:

push is not a function 

To begin, I initialized my arrays as empty and created an add function to use as the first argument:

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

var navBarArray = [];
var listArray = [];

var mapping = {
  ".navbar": navBarArray,
  ".list-group": listArray
};

My attempt to apply this on the mapping object resulted in errors:

var mapping = {
  ".navbar": Math.round(navBarArray.reduce(add, 0)),
  ".list-group": listArray
};

Unfortunately, I still receive the error 'push is not a function' in my console. As shown below, I have a function that adds values to the array. While I can further reduce it inside the function, it restricts access to the variable and increases the complexity of the function:

Object.keys(mapping).forEach(function(selector) { 
      $(selector).hover(function(evt) {
        console.log('mapping', mapping);
        console.log('selector', selector);
        enteredTime = new Date();
      }, function() {
        var ctime = new Date();
        var time = (ctime.getTime() - enteredTime.getTime()) / 1000;
        mapping[selector].push(time);

        // *********** this works but not where I need it to*******
        var reduce = Math.round(navBarArray.reduce(add, 0));
        console.log(reduce);
        });
    })

Answer №1

Revamp your mapping object to include distinct sections for the array and overall count:

let mapping = {
    "#header": {
        total: 0,
        instances: []
    },
    ".menu-items": {
        total: 0,
        instances: []
    }
}

Afterward, utilize

mapping[selector].instances.push(instance)
and calculate the total using:

mapping[selector].total = mapping[selector].instances.reduce(sum, 0);

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

Trouble with displaying class object array in Angular 5 using ngFor loop

I am attempting to loop through an array of class objects to populate a dropdown menu in Angular 5. However, the dropdown menu is not showing any options and there are no errors appearing in the browser console. The object array is created based on this m ...

Transferring SQL-generated JSON object from PHP to JavaScript

Seeking assistance with passing a JSON object from PHP to Javascript. The object is populated from an SQL Database using the following PHP code snippet. <?php $conn = mysql_connect("localhost","root",""); if(! $conn ) { die('C ...

What is the best way to add elements to a PHP array after cross-referencing it with another array using their keys?

Array1 ( [a]=>1; [b]=>2; [c]=>3 ) Array2 ( [a]=>1;[b] =>1 ) Desired output: Array1 ( [a]=>2; [b]=>3; [c]=>3 ) Is there a way to merge the values of Array1 with Array2 based on their keys? Any help would be appreciated. Thanks. ...

How can arrays be concatenated in Java?

I'm currently working on a method to concatenate two arrays, but I keep encountering the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2." It's puzzling me why this issue is arising. Can someone shed some light on wh ...

Issues with Angular ngroute: controllers are not functioning properly

In order to route my application with different themes on the same page, I plan to utilize the ngroute module. Here's an example of how I intend to achieve this: <html> <head> <title>Angular JS Views</title> ...

Unable to dynamically append items to Owl Carousel using JavaScript

I am currently working on adding items dynamically to an Owl carousel. This is how I am approaching it: HTML <div id="avatar-carousel" class="owl-carousel lesson-carousel"> <div class="item item-logo"& ...

Addressing the issue of empty ngRepeat loops

Utilizing ngRepeat to generate table rows: <tr ng-repeat="User in ReportModel.report" on-finish-render> <td><span>{{User.name}}</span></td> </tr> An on-finish-render directive triggers an event upon completion of t ...

Handling events in JavaScript within a loop

Here is a program I created using jQuery: $(document).ready(function(){ var k = 0; setTimeout(function(){alert("Hello")},500); for (var i = 0; i < 5000; ++i) { ++k; $('.inner').append('<p>Test</p>& ...

Unlocking the Power of Transition: Effortlessly Submitting a Form Post

After the modal finishes fading out, I want my form to be submitted and sent to the email file "refreshform.php". However, currently after the modal fades out, the form does not submit or post anything to the PHP file for sending the email. It simply fades ...

Anticipating the completion of a process.nextTick cycle

Problem Statement I am currently working on a Node.js application that involves complex calculations and utilizes recursive algorithms. The code snippet below gives a brief overview of how the calculations are performed: // routes.js - express.js routes ...

retrieve JSON information using jQuery

Hi everyone, I'm trying to figure out how to retrieve JSON data using an AJAX call. I attempted the following method, but it doesn't seem to be working :P First off, I created a JavaScript file where I stored my JSON data: var food = [ ...

In Internet Explorer 11, React 15.4.1 does not support using objects as valid child components

When trying to render a collection of children in React, make sure to use an array instead of objects. If you encounter the error "Objects are not valid as a React child," consider wrapping the object using createFragment(object) from the React add-ons. Do ...

I am looking to pass several parameters through the post method by utilizing ajax

Can someone assist me with this code? I am trying to pass the item ID, stock quantity, and price using AJAX in a POST method. Any help would be greatly appreciated. Thank you in advance! function updateItemDetails(itemId, sellingPrice, stockQty){ v ...

Accessing Elements by Class Name

I've been searching for information on the capabilities of getElementsByClassName for hours. While some sources mention it returns an HTML collection of items, length, and named items, w3schools provides an example where innerHTML is utilized: var x ...

The functionality of the .toggle method is limited to only being effective 1.5

I'm having an issue with making an image popup using the .toggle function in javascript. It seems to work initially, but then only works partially after that. When I click on the image, it opens as expected. However, when I try to close it by clickin ...

Utilizing express.js to access an HTML document

var express = require("express"); var fs = require('fs'); var sys = require('sys'); var app = express(); app.use(express.logger()); app.get('/', function(req, res){ fs.readFile('/views/index.html'); }); ap ...

What is the reason for innerHTML not functioning properly when trying to include HTML?

Apologies for my poor English, but I am determined to solve this issue using HTML code. <body> <div id="booklist"> <?php include("../templates/nav.php"); ?> <div class="hero"> <?php include("../templates/aside.ph ...

Implementing an Onclick function in HTML

I have an HTML code and I am looking to add an onclick event for a button named GET DATA. When the button is clicked, I want to send data for userId and categoryId to a PHP file. Can someone help me implement this functionality in my existing code? Here ...

Tips for inserting HTML-tagged data into a database using AJAX and PHP

var id=$("#id").val(); var status=$("#status").val(); var jtitle=$("#jtitle").val(); function submitData(){ var id=$("#id").val(); var status=$("#status").val(); var jtitle=$("#jtitle").val(); var jdesc=tinyMCE.acti ...

How to update an object property in React using checkboxes

I am currently navigating the world of react and have encountered a challenging issue. I am in the process of developing an ordering application where users can customize their orders by selecting different ingredients. My approach involves using checkboxe ...