Ways to eliminate empty values from an array in JavaScript

I need help deleting any null elements from my array

 [ [ null, [ [Array], [Array] ] ] ]

I am looking to restructure it as

[ [[Array],[Array]], [[Array],[Array]],  [[Array],[Array]] ]

If there are any undefined/null objects like :

[ [[Array],[]],  [[Array],[Array]],  [[Array],[Array]] ]

I want to eliminate the entire element [[Array],[]]

The 'yes' and 'no' messages indicate which elements have the undefined value. However, I have attempted filtering out by checking for null values but without success.

var filter = Total[0][i];

filter.forEach(e => {
    if ((e[0] !== undefined)&&(e[1] !== undefined)) {
        console.log('yes');
    } else {
        console.log('no');
        Total[0][i] = null;
    }
});

var totalArray = [];

const resultFilter = Total.filter(arr => arr != null);

var Filtereddata = resultFilter.filter(function(element) {
    return element !== null;
}

I am uncertain about how to effectively remove the element or filter them into a new array removing any null entries. The presence of null Arrays is causing formatting issues client-side with extra commas, hence it would be preferable to completely remove those indices/elements.

Answer №1

To effectively eliminate any null values within an array, you can utilize a recursive approach to filter them out:

 const removeNulls = arr => arr
    .map(el => Array.isArray(el) ? removeNulls(el) : el)
    .filter(item => item !== null);

If your goal is to also get rid of empty arrays, simply replace [] with null:

 const removeEmpty = arr => arr.length ? arr : null;

Next, modify the recursive function call from removeNulls(el) to removeEmpty(removeNulls(el))

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

Using D3.js to plot data points on a topojson map's coordinates

Having difficulty converting latitude and longitude coordinates to "cx" and "cy" positions on my SVG map created with d3 and topojson. Despite researching solutions online, I am unable to successfully implement the conversion process. Each time I try to co ...

Update the canvas box's color when you interact with it by clicking inside

I'm in the process of developing a reservation system and I'm looking to implement a feature where the color of a Canvas changes when clicked. The goal is for the color to change back to its original state when clicked again. Snippet from my res ...

Generating dynamic variable names in JavaScript

Looking for a similar solution. var item_<?php echo $variable->n ?> = <?php echo '32' ?> Trying to achieve something like this: var item_342 = '32' ...

How to correctly serialize nested maps in JQuery ajax data for sending?

var locationData = { "location" : { "name" : $("#user_loc_name").val(), "street_address" : $("#user_loc_street_address").val(), "city" : $("#user_loc_city").val(), "province" : ...

Having trouble with the functionality of Bootstrap's nav-tabs 'show' feature?

I'm having some issues with adding a search box to my glossary. The glossary is created using nested unordered lists (ul) within another ul that has classes of "nav-tabs" and "bootstrap". In the JavaScript code, I am using the following snippet: $j(& ...

Are there any JavaScript charting tools that can draw in a clockwise direction with multiple data points?

Can anyone recommend a JavaScript live chart/graph library that can create clockwise graphs with multiple points, similar to the example below? https://i.sstatic.net/dQfK4.png ...

Animation loading on React.js when the page or URL is changed

Just starting out with React and trying to incorporate a loading animation when the page/url changes on button click - check it out here: https://codesandbox.io/s/cthululel-7zmsl?fontsize=14 Successfully got the animation working on initial load, but runn ...

Angular dependency injection function

What is the best placement for the common handleError and handleSuccess functions? These functions are commonly used by every service. Where should these functions be placed? Should they be global functions injected as dependencies? (function () { "u ...

Not all elements are removed by an array

$channels = array('imaqtpies','imsoff','zzero71tv', 'kaptenen', 'onlySinged', 'nightblue3') ; $nr = 0; $callAPI = implode(",",$channels); $online = 'online.png'; $offline = ' ...

Retrieve information from an external JSON file and display it in a jstree

I am trying to pass JSON data to a jstree object from an external file. The code snippet I have does not seem to be working properly. <script> $.jstree.defaults.core.themes.responsive = true; $('#frmt').jstree({ plugins: [" ...

Periodically transmit information to a Google Script web application

I am currently working on a Google Script web app to automatically update data from a Google Sheet every 30 minutes. I initially attempted using the page refresh method, but encountered an issue where the web app would display a blank page upon refreshin ...

The outcome of the Javascript Calculator is showing as "Undefined"

I've been attempting to create a calculator using JavaScript, but I'm facing an issue where the 'operate' function keeps returning Undefined, and I can't seem to figure out why. I suspect that the problem lies with the switch state ...

Updating specific data in MongoDB arrays: A step-by-step guide

{ "_id":{"$oid":"5f5287db8c4dbe22383eca58"}, "__v":0, "createdAt":{"$date":"2020-09-12T11:35:45.965Z"}, "data":["Buy RAM","Money buys freedom"], & ...

``req.body is not being properly populated when data is sent using form-data, causing

When I send data in my Node.js application as raw JSON/x-www-form-urlencoded from Postman, it gets passed successfully. However, when sending the data as form-data from either Postman or my Angular frontend, the req.body is coming back as undefined. I have ...

Changing the color of a highlighted face on a PlaneGeometry in ThreeJS

I am trying to figure out how to change the color of a specific face when hovering over it in my PlaneGeometry, but I am having trouble getting the selected face. Below is the code I have so far: //THREE.WebGLRenderer 69 // Creating a plane var geometr ...

The output from VScode-Code-Runner is limited to just the directory, with no additional

I have successfully set up Code Runner with the following configurations in the Executer Map: { "explorer.confirmDelete": false, "[html]": { "editor.defaultFormatter": "vscode.html-language-features" }, "[javascript]": { "e ...

align all items centrally and customize Excel columns based on the length of the data

Is there a way to dynamically adjust the column width based on the length of data in an Excel report using PHPexcel? Additionally, how can I center all the data in the Excel sheet? Here is the current code snippet: <?php if (!isset($_POST['send&a ...

What could be the reason for the absence of 'server' and 'client'?

Trying to retrieve data from db.json but facing some challenges. Below is the content of my db.json file: { "posts": [ { "id": "react-hooks", "title": "React Hooks", "content": "The greatest thing since sliced bread!", "author": "ali" }, ...

What do you mean my cookie isn't working?

I'm going crazy over this! There's a cookie that was set from a response header with the sessionid, visible in dev tools on Chrome and Firefox, but document.cookie shows an empty string. This is what the cookie looks like: Name: sessionid Value ...

Is it possible for SqlCommand.ExecuteReader to automatically open the database connection?

Unusual behavior is happening on my website. I have a WCF Data service that provides JSON data to populate a jqGrid using javascript/ajax calls. In addition, there is server-side code that also accesses the same WCF service to retrieve data. Within my WC ...