Transform an array by mapping it to remove any empty elements

Supplied with:

let input = [0, 1, 2,,,,,7]

I am aiming for:

let output = [, 1, 22, 333, 4444, 55555, 666666, 7777777]

(meaning each value is equal to the key times the key)

How can I perform a map operation (or similar) on the input even if it contains empty values?
When using input.map(), the resulting array will be [, 1, 22,,,,,7777777] since map naturally skips over empty entries. The data could vary from strings, objects, numbers, etc., but for simplicity, numbers are used in this example.

Answer №1

To ensure all indexes are iterated over, including empty ones, it is recommended to fill the array before applying a mapping function.

let result = input.fill().map((_,index)=>{/*...*/});

Similarly, the mapping function provided as the second argument to Array.from can be utilized for this purpose.

let result = Array.from({length: input.length}, (_, index)=>{/*...*/});

Spread syntax does not ignore empty slots, so creating a copy of the array with spread syntax and using map on it can be beneficial. This approach also ensures that the elements at each index are accessible.

let result = [...input].map((elem, idx)=>{/*...*/});

Answer №2

map() function in JavaScript cannot handle empty values according to w3schools

The map() method does not process array elements that are empty.

To work around this limitation, you can either use a for-loop to iterate through the array:

out = [];
for (var i = 0; i < input.length; i++) {
    var item = input[i];
    if (item != null)
        out[i] = item.toString().repeat(item);
}

Alternatively, you can create a custom functor called mapx():

Array.prototype.mapx = function(fn) {
    var out = [];
    for (var i = 0; i < this.length; i++) {
        var item = this[i];
        // if (item == null) item = sherlockHolmesKnow();
        out[i] = fn(item, i);
    }
    return out;
};

and then apply it on the input array like this:

input.mapx( (val, index) => (val == null ? null : (val+'').repeat(val)) )

This will result in an output of ["", "1", "22", null, null, null, null, "7777777"].

We'll leave out the artificial intelligence aspect of guessing numbers in the empty slots for now.

Answer №3

Here is an alternative method that may seem lengthy but it gets the job done. By using a for loop, you can iterate through null values within an array.

arr=[0, 1, 2,,,,,7]
res=[]
f=false
for(let i=0;i<arr.length-1;i++){
  if(arr[i]!=undefined){
      res.push(Number(String(arr[i]).repeat(arr[i]))
  }
  if(arr[i]==undefined&&f==false){
    n = arr[i-1]  
    f=true
    res.push(Number(String(n+1).repeat(n+1)))
  }
  if(f==true && arr[i]==undefined){
     n = Number(res[res.length-1].toString().charAt(0))+1
      res.push(Number(String(n).repeat(n)))
    }
}
console.log(res)

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

Create a function signature that can take in any 2D integer array as a parameter, no matter how the user decides to input it

To provide a practical example: #include <stdlib.h> #include<stdio.h> void demonstrate_function(int size , int array[][size]); int main(void){ int x; /*Static 2D Array*/ int data[2][2]; /*Various Techniques for Dynamically Allocating 2D Ar ...

The aria-label attribute is not compatible with the Android Chrome browser when used on an input

Have you noticed that aria-label is not being read correctly on Android Chrome? For example: <input aria-label="test" type="text"> When using Android chrome, it reads "Editbox, double tap to edit, double tap to enter text". However, when using iOS ...

Every time I try to use AgGrid selectors, they consistently come back with null results, even though the

I currently have an ag grid in my application: <app-my-component> <ag-grid-angular [gridOptions]="gridOptions" (gridReady)="setGridReady()"> </ag-grid-angular> </app-my-component> When running Karma- ...

What is the best way to update setState when triggering an onChange event?

Here is the code snippet for a React component that handles cryptocurrency selection: import React, { Component } from 'react'; import { Select } from 'antd'; import { connect } from "react-redux"; class SelecionarCrypto extends Compo ...

Different ways to analyze elements from 2 arrays to hone in on specific values

I'm really struggling to solve this issue. I have two arrays - one for cars and the other for active filters. The cars array consists of HTML li tags with attributes like car type, number of seats, price, etc. On the other hand, the active_filters arr ...

The $http.get request is successful only when the page is initially loaded for the first

Imagine this scenario: a user navigates to http://localhost:3000/all, and sees a list of all users displayed on the page. Everything looks good so far. However, upon refreshing the page, all content disappears and only raw JSON output from the server is sh ...

Best practices for securing passwords using Chrome DevTools in React development

React developer tool inspector Is there a way to prevent password values from appearing in the inspector as a state when handling form submissions in ReactJS, especially when using Chrome's React developer tool? ...

Tips for preparing data prior to downloading it as a CSV file

Trying to export data as a CSV file, encountering an issue with the generated file content: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[ ...

How can I pass a value back to a koa generator function?

I currently have a setup similar to the following: var app = koa; var run = function (generator){ var it = generator(go); function go(err, res) { it.next(res); } go(); } app.use(function *() { run(function *(callback) { var res ...

Creating a multi-dimensional array from a CSV in Python: a step-by-step guide

I am looking to generate a multidimensional table based on data from a CSV file. The table should be organized by two concatenated columns. Here is an example structure of the CSV file (data is fictional): Year,Country,Sex,Population 1990,USA,M,178 1990,US ...

Selecting elements with jQuery allows you to manipulate the

Encountering issues with jQuery selectors. This is how my HTML looks: <form method="" action=""> <p id="question_1"> <h1 id="question">1. A Question</h1> <div id="choices"> ...

Warning: Stack Smashing has been detected after using the `fgets`

When entering two strings, string1 and string2, the goal is to remove any instances of the letters in string2 from string1. The issue arises with a stack smashing detection error occurring after inputting the second string. The rmchr function seems to work ...

Is there a way to verify the 410 status of an iframe?

I am currently developing a webpage that utilizes the Slideshare API to fetch a select number of presentations from a specific Slideshare user and display them through embedded iframes. Everything is functioning correctly for the most part, except for one ...

The CSS animation spills out of the div container

I am encountering an issue with my code where the borders are not displaying as expected. The screen is divided into 8 equal parts, each of which should have a ripple effect. While everything works well in Chrome, Mozilla, Opera, and Safari, the ripple eff ...

Is it possible to utilize PDF.js once the PDF file has been downloaded?

My goal is to integrate PDF.js (or Viewer.js) with a Flask application, where I have already retrieved the file from a server. Instead of using PDFJS.getDocument('helloworld.pdf') I prefer to display the downloaded PDF in the browser through a ...

Executing a TypeScript function through a package.json script: A guide

I'm currently using a javascript function from my package.json script, but I want to switch it to a typescript function in a typescript file. Can someone advise me on how to make this adjustment? This is the javascript code that runs the desired func ...

How can I properly retrieve data from a multidimensional JSON array using PHP?

I'm currently working on managing cookies that contain multidimensional JSON object arrays, and I seem to be facing a challenge in accessing them. Any assistance would be greatly appreciated. Here is an overview of the issue at hand: I extract values ...

Preserve Text Selection While Utilizing DIV as a Button

I wonder if this issue is specific to the browser I'm using? Currently, I'm using Chrome... My goal is to enable users to save any text they've highlighted on the page with their cursor. I've set up the javascript/jQuery/ajax and it w ...

Optimizing the JSON string configuration for PHP cURL usage

I have encountered two different examples. Example1: $data1 = "{'username':'myUserName','password':'myPassWord'}"; and Example2: $username= "myUserName"; $password= "myPassWord"; $data ...

Ajax is able to fetch a JSON string, however it struggles to iterate through the successful data as an

My current project involves creating a graph using d3.js. I came across some php code that fits my needs perfectly. However, I am working with c# and Visual Studio, so I need to convert it into asp.net. For starters, I want to input some hardcoded sample d ...