Is There a Sparse Array Element in JavaScript?

Is there a more efficient method to check for the presence of an array element within multiple layers of a structure? For example:

if (typeof arr[a][b][c] === 'undefined') { ...do something... }

If [a] or [b] are missing, we cannot accurately test for the existence of [c].

Are there any underscore or lodash functions that can assist with this scenario?

Answer №1

To optimize your code for reuse in multiple places, consider implementing a function:

function extractValue(inputObj, properties) {
  return properties.reduce(function(acc, prop) { return acc && acc[prop] ? acc[prop] : null }, inputObj)
}

if (extractValue(myArray, ['x', 'y', 'z'])) ...

This function can handle both objects and arrays:

var myObj = [0, {x: [0, 'result', 2]}, 2]
extractValue(myObj, [1, 'x', 1]) //=> 'result'
extractValue(myObj, [1, 'x', 8]) //=> null

Answer №2

When checking for a sparse array, simply checking if an item is undefined may not be enough. Instead, you can utilize the in operator for testing like this:

(x,y,z) in array

var x = [];
x[5] = 1;
y = 5;
console.log(1 in x)
console.log((1,2,3) in x)
console.log(y in x)

Answer №3

you have two options:

if (arr && arr[a] && arr[a][b] && typeof arr[a][b][c] === 'undefined') { ...do something... }

or you could implement a custom function for this purpose

function check(arr){
    let temp = arr;
    for(let i=1; i<arguments.length; i++){
        if(temp[arguments[i]] == undefined){
            return false;
        }
        temp = temp[arguments[i]];
    }
    return true;
}


let arr= [[[1], [2]], [3]];

console.log(check(arr, 0, 0));
console.log(check(arr, 0, 0, 0, 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

Implementing NPM commands in Jenkins using shell scripting

Whenever I attempt to run the "npm" command, I encounter a syntax error. Users/Shared/Jenkins/Home/workspace/projectName/npm test ^^^^ SyntaxError: Unexpected identifier This is the Jenkins Build shel ...

Swapping out a code snippet within an HTML document using JavaScript

As a new member of this community, I present to you my very first problem that needs solving. It might be a piece of cake for some of you, but for me, it's proving to be quite tricky. The task at hand involves replacing or removing a string to make ev ...

Foundation 4 - image hover effect to display alternate image

I am a newcomer to Foundation 4, but I have some coding experience. Currently, I am in the process of transitioning my photography blog (www.momentaryawe.com/blog) from Wordpress with a custom theme to a custom theme built on Foundation 4. Most aspects of ...

Utilize a WCF Service with HTML and JavaScript

FILE WebService.svc.vb Public Class WebService Implements IWebService Public Function Greetings(ByVal name As String) As String Implements IWebService.Greetings Return "Greetings, dear " & name End Function End Class FILE IWebServ ...

Tips for generating an input element using JavaScript without the need for it to have the ":valid" attribute for styling with CSS

My simple input in HTML/CSS works perfectly, but when I tried to automate the process by writing a JavaScript function to create multiple inputs, I encountered an issue. The input created with JavaScript is already considered valid (from a CSS ":valid" sta ...

Best practice for stopping routing in angular

I am currently working on an angular application that includes guest functionality. This feature allows me to create a guest account for all unauthorized users in the background. I need to pause routing until the guest account is created and then specify a ...

Guide on merging the root route with child routes using react router v6

When a user visits "/", I want it to automatically redirect them to "/todo", but this functionality is not working as expected. let router = createBrowserRouter([ { path: "/", element: <Layout />, children: ...

picking out a particular set of data from a JSON document

I have a map of Europe along with a JSON file that displays the unemployment rate for each country in the year 2011. The JSON file also includes x and y elements, allowing me to place a blue circle on top of each country on the map. My goal is to be able ...

Tips for navigating through an array incrementally in a Controller using input provided by the user in the View

Greetings, I am currently working on a small website project using WAMPserver. The site is structured following an MVC design pattern. In one part of the process, I generate an array of strings in the controller. My goal is to display each element of this ...

Preventing an infinite re-render loop caused by event listeners in React

One functional component is causing me some trouble: export default function Nav({photo}) { const [isOpen, setIsOpen] = useState(false) const [width, setWidth] = useState(window.innerWidth); const breakpoint = 768; useEffect(() => { ...

Using jest in typescript to simulate HttpRequest body and InvocationContext in @azure/functions

I have the following function and I am trying to write a test for it, but I'm having trouble figuring out how to mock HttpRequest import { app, HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions"; export async function ...

Are React component properties enclosed in curly braces?

I have a new component configured like this: type customType = differentType<uniqueType1, uniqueType2, uniqueType3>; function customComponent({q}: customType) When called, it looks like this: <customComponent {...myCustomVar} />, where myCus ...

I've been attempting to relocate a CSS element at my command using a button, but my previous attempts using offset and onclick were unsuccessful

I am trying to dynamically move CSS items based on user input or button clicks. Specifically, I want to increment the position of elements by a specified number of pixels or a percentage of pixels. Currently, I am able to set the starting positions (top a ...

The Checkbox handler in Material-UI component fails to update the state - Version 5.0

Hey everyone, I'm facing an issue with my "Checkbox" component in React. After clicking on it, the state doesn't update to 'true' as expected. The checkbox works visually in the DOM but the state remains 'false'. Can someone p ...

Is there a similar function in AngularJS that is equivalent to getJSON? Just curious, as I am new to this

As a beginner in javascript, angularJS, and JQuery, I recently embarked on programming an angularJS app that involves using JQuery to fetch JSON data from a webserver. Here is the code snippet I am working with: var obj = $.getJSON( "http://something.com/ ...

Best practice for resetting jquery datatables for proper functioning

A user on Stack Overflow was seeking a solution for working with DataTables.js and a variable number of columns. The provided solution can be found here: http://jsfiddle.net/gss4a17t/. It's worth noting that this solution relies on a deprecated funct ...

It is not possible to recycle a TinyMCE editor that is embedded in a popup

Having a frustrating issue with the TinyMCE Editor plugin embedded within a Fancybox pop-up window. I have a list of objects with Edit links that trigger an AJAX call to retrieve content from the server and place it in a <textarea>. A TinyMCE editor ...

Deactivate Search Functionality for Users who are not Logged in on an Angular 2 Application

The login component and view are functioning as intended, preventing users from accessing AuthGuard protected routes if they're not logged in. However, I'm facing a challenge with the search bar displayed on the home login screen (actually presen ...

Ways to provide input parameters to a method upon clicking an element without using the HTML onclick attribute

Is there a way to pass data between pages without redirecting to the next.php page every time a button is clicked? One suggestion is to remove the onclick attribute from the button: <button class="submit-btn"></button> and use this jQuery fu ...

Accessing the camera or photo library in React Native does not require any permissions

In my current project, I am developing an app that requires users to upload images from their photo library or camera. To access the camera functionality, I am utilizing the react-native-image-picker library without integrating react-native-permissions. ...