Discovering the indices of undefined array elements in JavaScript without using a loop

Is there a way in JavaScript to retrieve the indexes of undefined array elements without using a loop? Possibly utilizing a combination of map, filter, and indexOf?

I have a loop solution that I'm seeking an alternative for - something more concise, like a one-liner:

const sourceArray = [,1,undefined,3];
const filteredArray = [];

for (let i = 0; i < sourceArray.length; i++) {
  if (sourceArray[i] === undefined) filteredArray.push(i);
}

console.log(filteredArray); // [0,2]

Answer №1

If you want to create a new array based on specific values and indices, you can use the Array.from method in JavaScript.

Array.from is particularly useful for generating arrays without any gaps, which can then be easily filtered.

const
    originalArray = [, 1, undefined, 3],
    newArray = Array
        .from(originalArray, (_, index) => index)
        .filter(index => originalArray[index] === undefined);

console.log(newArray); // [0, 2]

Answer №2

Here is an example of a less than ideal solution, provided for comparison:

let arr1 = [0, , 2, undefined, 4, , 6];
let arr2 = [];
let arr3 = arr1;
let index;
while ((index = arr3.findIndex(val => val === undefined)) > -1) {
  if (arr2.length)
    arr2.push(arr2.at(-1) + index + 1);
  else
    arr2.push(index);
  arr3 = arr3.slice(index + 1);
}
console.log(arr2);

Not the most efficient code, right? I was intrigued by the fact that findIndex() does not ignore empty array elements like indexOf() does. However, it only identifies the first instance of a value, necessitating slicing the array in each iteration to make it function. I wrote and tested it on jsfiddle just to observe its performance. The outcome speaks volumes.

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

The steps to display a partial view within another view in React Native

Attempting to show the View after calling alert("Hi") in the renderMoreView function has been challenging for me. The alert works fine, but displaying the View is where I am encountering issues. class Main extends Component { state = { moreButton: f ...

Navigating race conditions within Node.js++]= can be challenging, but there are strategies

In the process of developing a MERN full stack application, I encountered a scenario where the frontend initiates an api call to "/createDeckOfCards" on my NodeJS backend. The main objective is to generate a new deck of cards upon clicking a button and the ...

Masking Aadhaar numbers

I need to find a way to detect when the back button is pressed on an input field. The methods I have tried, e.key and e.which, are returning as undefined in mobile Chrome. How can I make this work? It's functioning properly on desktop. jQuery(funct ...

Discover how to handle JSON arrays that contain empty or blank fields with Jackson library

Currently, I am utilizing Jackson for parsing a jsonString with the following structure: { "key": "Flowers", "colorized": true, "values": [ [1472428800000, , "#aaaaaa", "", ""], //empty or blank field [1472515200000, , "#bbbbbb", "", ""], ...

How to Conceal the <th> Tag with JavaScript

I attempted to conceal certain table elements using JavaScript. For <td> elements, it works fine: function hide(){ var x=document.getElementsByTagName('td'); for(var i in x){ x[i].style.visibility='hidden'; ...

I'm curious, is there a maximum limit for numeric array keys in PHP

I've encountered an issue with arrays in PHP where the keys are being unexpectedly changed. In the example below, I start with a string but somehow it's getting converted to an integer and altering the key when added to another array. Code ----- ...

Learn how to establish a state using an array and effectively utilize the setState() method in React

For my latest project, which is API based, I am working with arrays that contain sub-arrays. How can I define a state with an array and utilize the setState() method to work with the entire array? ...

Encountering difficulties accessing functions from apollo-server-express

I have been following a tutorial and attempting to launch the node server, but I am unable to import these functions from the Apollo package const {graphqlExpress, graphiqlExpress} = require('apollo-server-express'); // importing functions here ...

If you refer to a function, are you personally calling the function or asking the reference to call it?

From what I understand, and please correct me if I'm mistaken, when a variable is assigned to a function in the form of a function expression, it doesn't hold the function in the same way that it holds a primitive value. The variable simply refer ...

The challenges encountered with JSONP/Ajax Script - displaying 'Undefined'

I need help retrieving data from a webserver that I don't have control over. I've searched online but haven't found a solution yet. I've tried various codes, with and without DataTables. If anyone could provide guidance on where to go ...

Using the ng-repeat directive in an angular-nvd3 tooltip

Looking to dynamically repeat values in the tooltip content of an nvd3 graph? Not sure how to achieve this using ng-repeat with JSON data? Seeking guidance on alternative methods? I can help! $scope.options = { chart: { type: ...

Having trouble retrieving the value from the input field with Angular.js

I am having trouble retrieving the value from an input field using Angular.js. Below is the code explanation. Here is my controller code: $scope.shipping=0; $scope.addProductInfoData=function(billdata){ console.log('valid',$scope.shippi ...

Encountering a Problem with Chart.js Library During Online Tutorial on YouTube

Currently, I am immersed in a YouTube tutorial that guides me through the process of creating an expense tracker application. However, as I diligently follow the steps outlined in the tutorial, I encounter a hiccup along the way. Instead of witnessing the ...

Seeking assistance with producing results

Is there someone who can provide an answer? What will be the output of the code snippet below when logged to the console and why? (function(){ var a = b = 3; })(); console.log("Is 'a' defined? " + (typeof a !== 'u ...

The issue of not being able to go fullscreen with a YouTube iframe nested within another iframe

I have a YouTube video embedded inside another iframe, but I am facing an issue where the fullscreen feature is not working even after enabling all the required attributes. If the video isn't displaying properly in the code snippet below, you can vie ...

Using an external npm module in TypeScript can result in the tsc output directory being modified

In my TypeScript project, I have set up the build process to generate JavaScript files in the ./src/ directory. Everything works smoothly when building against existing npm modules, such as Angular 2 imports. However, I encountered a strange issue when I ...

Changing the appearance of a specific child component in React by referencing its id

There is an interface in my code. export interface DefaultFormList { defaultFormItems?: DefaultFormItems[]; } and export interface DefaultFormItems { id: string; name: string; formXml: string, isDefaultFormEnable: boolean; } I am looking ...

The handleClose() function in React is currently writing to the console but failing to close the child element

Currently, I am in the process of creating a small online store for my personal business. Although I have limited experience with React, I believe I have managed to make some progress and might be able to complete something that is at least functional, eve ...

Retrieve the element's value in relation to a different parent element

[JavaScript] How can I access the value of a textbox related to a button through jQuery? The event is triggered when the .button-action is clicked <td class="dmsInput"> <input type="text" maxlength="4" size="4" class="d"> </td> <td& ...

Prevent the execution of a post request function depending on the promise result?

When I handle a POST request in express, I am required to retrieve data from a mongoDB cluster and then respond accordingly based on the retrieved response. app.post('/api/persons', (req, res) => { const data = req.body; if (!data.name || ...