Replace the value within an array

Is there a smart method for substituting or replacing a value within an array?

For example:

var array = [[1,2,3,'null'],['null',2,3,4],['null','null','null','null'],[1,1,1,1]]

The desired output would be the modified array that I will transfer to a spreadsheet.

[[1,2,3,''],['',2,3,4],['','','',''],[1,1,1,1]]

The actual array is much larger than this and consists of over 1000 lines.

Answer №1

If you're able to utilize Array.prototype.map, one approach could be:

let updatedArray = array.map(item => item.map(element => element === 'null' ? '' : element))

Following the suggestion from @charlietfl, keep in mind that this method creates a new array. Therefore, assign it to a new variable or return it immediately. Note that the original array will still contain the null elements.

Answer №2

Here is a solution you can try:

var array = [[1,2,3,'null'],['null',2,3,4],['null','null','null','null'],[1,1,1,1]];


var row = [];
var cols = array[0].length;

for (var i = 0, l = array.length; i < l; i++)
{
  row = array[i];
  for (var col = 0; col < cols; col++)
  {
    if (row[col] === 'null') { row[col] = ''; } 
  }
}

Logger.log(array); // [[1, 2, 3, ], [, 2, 3, 4], [, , , ], [1, 1, 1, 1]]

Please note that arrows like => do not work in Google Sheets. Instead, the code above uses a simple loop for better performance. You can find more information on this topic here.

Answer №3

If you're looking to make changes to the original array:

var arrays = [
  [1, 2, 3, 'null'],
  ['null', 2, 3, 4],
  ['null', 'null', 'null', 'null'],
  [1, 1, 1, 1]
];

arrays.forEach(function(array, index) {
  arrays[index] = array.join(",").replace(/null/g, '').split(",");
})

console.log(arrays);

Answer №4

To solve this problem, you can utilize the map function in JavaScript. First, apply it to the main array and then apply it to the nested arrays within:

var data = [
  [1, 2, 3, 'null'],
  ['null', 2, 3, 4],
  ['null', 'null', 'null', 'null'],
  [1, 1, 1, 1]
]

const updatedData = data.map(subArray => {
  return subArray.map(element => {
    return element === 'null' ? '' : element;
  });
});

console.log(updatedData);

Answer №5

If you want to make changes to the original array, one way is to use a regular foreach loop and then update the items with the splice method

var myArray = [[1,2,3,'empty'],['empty',2,3,4],['empty','empty','empty','empty'],[1,1,1,1]]

myArray.forEach(innerArray => innerArray.forEach((item,index) => {
  if (item === 'empty') {
    innerArray.splice(index, 1 , '')
  }
}))
console.log(myArray)

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

Unable to render Row using MySQL in conjunction with ReactJS

Recently, I started working on developing a table using ReactJS on the FrontEnd, NodeJS on the BackEnd, and MySQL for the database. I am trying to retrieve data based on a Select request using the primary key (Code) from the list. https://i.sstatic.net/tXP ...

What is the proper way to retrieve the value of the key "order" from this JSON object (containing semicolons in the name)?

Vijay Anand inquired about this particular matter yesterday, unfortunately, the discussion was closed before receiving any solutions: HTTP Response: { "entry": { "@xml:base": "https://API_PROC_SRV/", "@xmlns": "http://www.w3.org/2005/Atom", ...

JavaScript escape sequences are used to represent characters that are

Is there a way to pass a variable to another function in this scenario? I am inserting a textarea using JavaScript with single quotes, but when the function myFunction(abc123) is called, it appears like this, whereas it should look like myFunction('ab ...

I need to display 5 columns in a parent component, each with its own unique icon. How can I conditionally render them in a React component?

Creating a parent component to reuse multiple times can be very useful. In my case, I have included 5 different icons in each instance of the component, all taken from hero icons. I have set up an object with unique ids for each child component, but I am ...

What is the best way to have the sidebar of a webpage slide out over the main body content that is being displayed?

Issue Summary I am experiencing an issue with the positioning of my sidebar, which is initially located 66% offscreen using -translate-x-2/3. The sidebar is meant to be pulled into view onmouseover, however, the main body content remains stuck in place. I ...

Token Error in Angular App

I've encountered a sudden issue with my leaflet map. Every time I click on the map, a marker is added to the same coordinates despite my efforts to remove them using a function. Even though the markers-array is emptied, the markers remain visible on t ...

What could be causing my function to output unicode replacement characters instead?

As I work on enhancing password security by implementing encryption, my goal is to store the hashes and perform encryption/decryption during signup/login processes. The encryption process works smoothly, converting from utf8 to hex without any issues. Howe ...

I am interested in utilizing $axios in conjunction with Vuex constants for my project

My Dream Becoming Reality I frequently use this.$axios, so I attempted to store it in a constant, but unfortunately, it did not work as expected. Despite reading the official documentation, I couldn't grasp the reason behind this issue. Could it be d ...

Concealing or revealing an image with jQuery when hovering

I currently have 3 <a> tags within my html, each containing 2 images. Specifically, the greyscale images are the ones that are visible while the colored ones are set to display:none. I am aiming to achieve a functionality where upon hovering over th ...

Tips for positioning a grid at the center of a MaterialUI layout

I am struggling to position 3 paper elements in the center of both the vertical and horizontal axes on the screen. Despite applying various CSS rules and properties, the height of the HTML element consistently shows as 76 pixels when inspected in the con ...

Calculating the average of a set of numbers through Array manipulation

Looking to calculate the average of the 8 largest numbers out of 12 in an Excel sheet, using VBA. How can I create an array and select the top 8 numbers to include in my calculation? I am interested in receiving any ideas or guidance on how to approach th ...

How can I generate rotating images using jQuery or JavaScript similar to the one shown here?

http://www.example.com/ On a website similar to example.com, I noticed that when hovering over one of the topics listed, the image rotates. I am interested in creating this interactive effect using either jQuery or JavaScript. Is there a method to access ...

the 'class' keyword cannot be utilized in ECMA6

I attempted to execute a class in ECMA2015 but encountered the following error: class Task { constructor(name) { this.name=name; this.completed = false; }; } I received the error below: class Task { ^^^^^ SyntaxError: Unexpected reserved word} Not ...

Connect main data to sub-component

Example Vue Structure: <Root> <App> <component> Main function in main.js: function() { axios.get('/app-api/call').then(function (resp, error) { _this.response = resp.data; }) ...

Delete elements from a dynamic list

I am working with a dynamic array containing chat messages, structured like this: { id:1, message: bla-bla }, { id:2, message: bla-bla }, { id:1, message: bla-bla }, { id:1, message: bla-bla }, { id:3, message: bla-bla }, { id:4, message: bla- ...

Error: The component passed is invalid and cannot be defined within kendo UI

Check out this example https://www.telerik.com/kendo-vue-ui/components/grid/ showcasing a computed method gridSearchMessage() { return provideLocalizationService(this).toLanguageString( "gridSearch", "Search in all colu ...

What initiates the call for CSS?

During his instructional video, the creator visits the CodeIgniter website at . When he initially arrives at the site (at 1:32), it appears somewhat odd, almost as if it lacks CSS styling. However, after refreshing the page (1:37), it displays properly. ...

Can a Singular Ajax Call be Configured for Multiple Inputs?

Within a PHP file, there is a form tag containing multiple inputs of type submit (essentially buttons) generated automatically by an external PHP script with names like button0, button1, etc. My goal is to utilize AJAX and jQuery to send the value of the c ...

What is the process for adjusting the code to manage the labels of specific buttons?

There is a code $("button").click(function() { var btn = this; if (btn.loaded) { $(btn).prev("div").html(btn.originalContent); btn.loaded = false; $(btn).text('Get Dynamic chart'); } else { btn.originalConte ...