What is the method for determining the length of a JavaScript "array"?

Lately, we've been heavily using javascript arrays and hashes and trying to find a universal way to count the items in both without needing to differentiate between the two. The .length method has proved to be unreliable as it only returns the value of the highest index in an array. The code snippet below attempts to solve this issue, but runs into problems with hashes returning inaccurate length values. We initially switched to Object.keys().length, but faced compatibility issues with older browsers like IE8.

We're stuck on such a simple problem and need some guidance. Help me, Obi Wan Kenobi. You're my only hope!

function isNullOrUndefined(aObject) {
    "use strict";
    return (typeof aObject === 'undefined' || aObject === null);
}

function count(aList) {
    "use strict";
    var lKey = null,
        lResult = 0;
    if (!isNullOrUndefined(aList)) {
        if (aList.constructor == Array) {
            lResult = aList.length;
        } else if (!isNullOrUndefined(Object.keys)) {
            lResult = Object.keys(aList).length;
        } else {
            for (lKey in aList) {
                if (aList.hasOwnProperty(lKey)) {
                    lResult++;
                }
            }
        }
    }
    return lResult;
}

Answer №1

Object.keys polyfill taken directly from the ES5-shim repository

// Custom implementation of ES5 15.2.3.14
// Source: http://es5.github.com/#x15.2.3.14
if (!Object.keys) {
    // Reference for safer Object.keys compatibility
    var hasDontEnumBug = true,
        dontEnums = [
            "toString",
            "toLocaleString",
            "valueOf",
            "hasOwnProperty",
            "isPrototypeOf",
            "propertyIsEnumerable",
            "constructor"
        ],
        dontEnumsLength = dontEnums.length;

    for (var key in {"toString": null}) {
        hasDontEnumBug = false;
    }

    Object.keys = function keys(object) {

        if ((typeof object != "object" && typeof object != "function") || object === null) {
            throw new TypeError("Object.keys called on a non-object");
        }

        var keys = [];
        for (var name in object) {
            if (owns(object, name)) {
                keys.push(name);
            }
        }

        if (hasDontEnumBug) {
            for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
                var dontEnum = dontEnums[i];
                if (owns(object, dontEnum)) {
                    keys.push(dontEnum);
                }
            }
        }
        return keys;
    };

}

Answer №2

Although Raynos may have provided a valid answer, it is important to consider performance.

Here is an example of my hash object:

function Hash(){
   this.values = [];
   this.keys = {};
}
Hash.prototype.set = function(key, val){ 
   if(this.keys[key]){
      this.values[this.keys[key]] = value
   }else{
      this.keys[key] = (this.values.push(val)-1)
   }
}
Hash.prototype.length = function(){
    return this.values.length
}

The reason I implement this structure is for performance reasons. Iterating through an object to determine its length can be inefficient, whereas the solution above provides direct access at all times.

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

Tips for identifying if the cursor is hovering over the :before or :after section of an element

One of the challenges I am facing involves CSS and defining drop areas for users to interact with, allowing them to either drop a section before or after existing sections. .section:before, .section:after { content: "[insert here]"; height: 64px; ...

What is the best way to delete the "Click to sort Ascending" text from the header of each column in a bootstrap-vue table?

Recently, I came across a bootstrap-vue table that caught my attention: https://i.sstatic.net/5jENs.png Below is the code snippet for the table setup: <template> <div class="container"> <h1 class="pt-2 pb-3">Bo ...

Create a randomized string of numbers that includes specific digits while excluding others

I am struggling with generating strings in JavaScript. Specifically, I have an array of numbers from which a string needs to be generated. The string must contain at least 1 number from the array, but must not contain a specific number given by the user. A ...

Can anyone tell me the best way to access the name attribute of an HTML element in TypeScript?

Currently, my code is utilizing the name attribute to verify whether the user has entered information in a specific field and validating the input. However, I am facing an issue where the submit button remains active even if there are empty fields presen ...

Double check for any identical items before proceeding to add them

Hey there! I need some help with pushing new items to an array without duplicating any elements. I've tried using this example, but it didn't work with our code. If anyone has a better solution or can spot where we're going wrong, please l ...

Displaying the most recent queries retrieved from a search API

Our web application built on angular.js utilizes a REST search API to query users within the system. The endpoint for searching users is: search/user?q='abc' Upon revisiting the web application, we aim to display the user's recent search ...

Currently, my goal is to create PDFs using Angular

<button class="print" (click)="generatePDF()">Generate PDF</button> Code to Generate PDF generatePDF(): void { const element = document.getElementById('mainPrint') as HTMLElement; const imgWidth = 210; ...

React Infinite Scroll - Issue with Intersection Observer API causing constant jumping back to the top

I am currently working on a React application that implements infinite scrolling using the Intersection Observer API without relying on any third-party libraries. My backend system is properly set up for pagination, and the infinite scrolling feature succe ...

"Identifying Mouse Inactivity in React: A Guide to Detecting When the Mouse

I need to dynamically control the visibility of a button element based on mouse movement. I am able to show the button when the mouse is moving using onMouseMove, but I'm stuck on how to hide it when the mouse stops moving. React doesn't have an ...

Using only Node.js, demonstrate the image

I want to show an image using only Node.js without involving HTML or ID's. I have been looking for solutions but most examples I find use HTML, which I prefer not to use. Unfortunately, I don't have any code to share, but I'm wondering if th ...

Issues with the functionality of the shopping cart are causing a disruption

This is the coding for the online shopping cart: <!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8" /> <title>Online Shopping Cart</title> <script src="jquery-3.1.1.min.js"></script> ...

Updating the status of a 2D array with N elements in React: A step-by-step guide

Before I dive into the topic, I must acknowledge that I have come across questions similar to this one before but was unable to find a solution on my own. Updating React state as a 2d array? Let's imagine this as my state object state = { graph ...

JSON Serialization of numeric data types

It came to my attention that the website generates the same Base64 string for payloads containing numerical values written in different notations. An interesting example is the output for these two payloads: { "value": 0.000001 } { "val ...

5 steps to create a versatile function for activating attributes based on their values

Hey everyone! I was working on creating this calculator and I had different options to implement it, but I wanted to do it in a specific way. <form action=""> <label for="num1">Number A</label><br> <input type="number" na ...

What is the most effective method to retrieve the current browser URL in Angular 2 with TypeScript?

Is there a way for me to retrieve the current URL from the browser within my Angular 2 application? Usually in JavaScript, we would use the window object for this task. Can anyone guide me on how to achieve this in Angular 2 using TypeScript? Appreciate a ...

Creating a distinct value in Master details within Angularjs

Utilizing AngularJS, I am fetching data from an API and displaying it on an HTML page. The issue arises when the SQL query, which involves a join between two tables (departments and employees), repeatedly fetches department data for each employee. My goal ...

"Encountering issues when trying to retrieve a global variable in TypeScript

Currently facing an issue with my code. I declared the markers variable inside a class to make it global and accessible throughout the class. However, I am able to access markers inside initMap but encountering difficulties accessing it within the function ...

Show the button only when the text is updated

Is there a way to display a button only when the quantity of items in the cart changes, similar to the eBay shopping cart feature? I was able to implement it but it's not functioning as expected. Here is the link to what I have so far. Does anyone kno ...

What is causing the issue with mongoose populate not working when trying to populate an array?

My database setup includes 2 schemas: const mongoose = require('mongoose'); const PinSchema = new mongoose.Schema({ title: String, content: String, image: String, latitude: Number, longitude: Number, author: { type: mongoose.Sch ...

I just made an ajax call. Now, how should I proceed with formatting the data that was returned

The ajax request below is functional, but not without its challenges. Working with HttpContext has proven to be difficult, as even Context.Response.Clear() does not seem to have any effect. How can I output only the desired content without any extra infor ...