Limit the application of the map() function to a single column within a 2-dimensional array in JavaScript when using Find and Replace

I have been using Google Sheets for my work

Recently, I came across a find and replace function that I found here. This function works perfectly when the array is generated from a single column of data.

However, there are certain cases where I need to use this function with all my data stored in an array that has been passed from previous processing. The formatted data looks like this when printed on the page:

| Id | Segment            | Other Column | etc..
|----|--------------------|--------------|
| 1  | AAA AA|AA|CaaL AA   | stuff        |
| 2  | AAA-AA|AA|CaaL      | stuff        |
| 3  | AAA, AA|AA|AA       | AA           |
| 4  | AA                  | stuff        | 
| 5  | AA AA               |              |
| 6  | AA, AA              | AA           |
| 7  |                     | stuff        |
| 8  | CaaL                | stuff        |
| 9  | AA                  | stuff        |

My goal is to only replace data in the Segment column:

| Id | Segment           || Other Column | etc..
|----|-------------------|---------------|
| 1  | AAA AA|zz|CaaL AA  | stuff         |
| 2  | AAA-AA|zz|Bob      | stuff         |
| 3  | AAA, AA|zz|zz      | AA            |
| 4  | zz                 | stuff         |
| 5  | AA AA              |               |
| 6  | AA, AA             | AA            |
| 7  |                    | stuff         |
| 8  | Bob                | stuff         |
| 9  | zz                 | stuff         |

The issue I face is that the AA in the Other Column (or any other column) gets replaced inadvertently, which is not desired.

Is there a way to restrict the findReplace function to update values only in a specific column within the values?

I tried to target the desired column using the following script:

function getColumn(matrix, col, startrow){
       var column = [];
       for(var i=startrow; i<matrix.length; i++){
          column.push(matrix[i][col]);
       }
       return column;
}

and then attempted to isolate the input to this column:


function fr(input) {
    const aCOL = getColumn(values, 2, 0)
    return input.aCOL.map(c => c.replace(regex, (x) => map[x]));
    
AND
   
   return input.map(c => c.aCOL.map(y => y.replace(regex, (x) => map[x])));

  }

Unfortunately, I encountered an error saying

Cannot read property 'map' of undefined
.

Thank you for any assistance provided.

function findReplace(values) {

  var search_for   = ["AA", "Caal"];
  var replace_with = ["zz", "yy"];
  
  var map = {};
  search_for.forEach(function(item, i) {
    map[item] = replace_with[i];
  });
  //map = { AA: 'zz', Caal: 'yy' };

  const regex = new RegExp("(?<![^|])(?:" + search_for.join("|") + ")(?![^|])", "g");
  
  range.setValues(values.map(fr));

  function fr(input) {
    return input.map(c => c.replace(regex, (x) => map[x]));
  }
}  

Answer №1

The solution provided in your previous query is effective, especially when you just need to adjust the range being retrieved. Instead of creating a separate function to extract the column into an array, you can simply modify the range.

If you are looking to replace the column labeled 'Segment', which is currently the second column, you can make the following adjustments.

Original Code Snippet:

const col = ss.getRange(2, 3, ss.getLastRow()).getValues();
...
ss.getRange(2, 3, ss.getLastRow()).setValues(col.map(fr));

Revised Code Snippet:

const col = ss.getRange(2, 2, ss.getLastRow()).getValues();
...
ss.getRange(2, 2, ss.getLastRow()).setValues(col.map(fr));

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

Inconsistencies observed during the native JSON import process in JavaScript

Encountered a strange behavior when loading a JSON file into JavaScript while working on a React project. Seeking an explanation and guidance on properly accessing data from the JSON data store. The JSON file contains product data: { "product ...

Is there a way to fix the issue of ContextMenu not appearing at the right position within a scrollable

I have a div within an iframe that needs to display a context menu when right-clicked. The div's length may exceed the visible area, making it scrollable. However, the issue I am facing is that the context menu appears in a different position than whe ...

Steps for updating a JSON entry in a Node.js environment

What is the best way to update a JSON value using node.js? I have come across a few examples online, but my situation is a bit more complex. I am able to access the value that needs to be modified var contents = fs.readFileSync("./../../skill.json"); var ...

What is the process for updating JSON using TextFields?

I am currently facing an issue with my TextFields displayed within a material-ui dialog. These TextFields are initially populated by JSON data, which you can see in the example below. The problem is that once the TextFields are populated, I am unable to up ...

Retrieve every row and store it in an array using phpMyAdmin

Hello, I'm experiencing some difficulty retrieving data from my phpMyAdmin and displaying it as JSON. Here is the current state of my PHP code: <?php $user = ''; $password = ''; $con=mysqli_connect("localhost",$user,$password, ...

Ways to implement variable face sizes in three.js meshes

Recently, I dove into the world of three.js and started playing around with it. I've been pondering whether there's a way to add some randomness to the size of the faces in a mesh created from their existing geometries. While three.js is fantast ...

Using AngularJS to add an element to an array based on a specified condition

dashboardCtrl Data app.controller('dashboardCtrl', ['$scope','$rootScope', function ($scope, $rootScope) { //Color $scope.Color = [{ colorname: "Red", number: "(3)" }, { colorname: "Brown ...

Open Zurb Foundation Reveal Modal from the bottom of the screen

Struggling to make the reveal modal open from the bottom of the window. Any assistance would be highly appreciated. I've been attempting to tweak the open function with the reveal js, as seen in the original code below. Thank you, P open : function ...

Disable the resizing and responsiveness features in the jQuery Basic Slider

I'm currently utilizing the Basic jQuery Slider from the Basic Slider website, and I am attempting to eliminate the responsive/resize feature. My goal is to keep the slider contained within a centered div without changing its size. However, whenever I ...

Node and browser compatible JavaScript logging library for effective logging experience across platforms

Our team is utilizing Visionmedias debug library, as it seamlessly functions on both browsers and Node.js environments. We are in search of a more reliable alternative to debug that offers the same level of functionality (error, warn, info, etc) for both ...

Send JSON data that has been refined utilizing jQuery

I am attempting to create a filtered JSON response using jQuery following a successful GET request of the original JSON response. The initial JSON response is an array of products from our Shopify store for the specific collection page the user is viewing. ...

What is the process for transmitting information via a Link in Next.js?

In my upcoming 13.1.5 version, I am faced with a challenge of sending the value of contact.name through a Link in my component. I am looking for the most effective approach to achieve this. The initial code block for the Link represents my original code. ...

Detecting modifications to an array with MobX

Today marks my first foray into learning MobX and I am eager to discover how to track all array changes (insertions, deletions, etc) with MobX. A practical example would definitely help clarify this: const TodoList = ({todos}) => ( <ul> ...

In Vue.js, utilize a contenteditable div to dynamically add an HTML element and bind it with v-model

Below is the HTML code I have written. <div id="app"> <button @click="renderHtml">Click to append html</button> <div class="flex"> <div class="message" @input="fakeVmodel" v-html="html" contenteditable="true">< ...

using reactjs to dynamically render elements based on the selected condition in a select box

Is there a way to dynamically change an element based on the selected value of a dropdown in React? I'm looking for help with rendering conditions. Here's a snippet of my code: <Col span={12}> <Form.Item label='Qu ...

Ways to extract subarray elements that meet a certain condition and break out of the loop

const winningTemplate = { firstRow: [0, 1, 2, 3, 4], secondRow: [5, 6, 7, 8, 9], thirdRow: [10, 11, 13, 14], fourthRow: [15, 16, 17, 18, 19], lastRow: [20, 21, 22, 23, 24], firstDiagonal: [0, 6, 18, 24], firstColumn: [0, 5, 10, ...

In HTML5, a full-width video exceeds the size of the screen

When I have a video set to full width in a header with the width at 100%, the issue arises with the height. The video is too large, causing the controls to be out of view unless I scroll. Is there a solution to remedy this problem? <video width="100%" ...

Guide to retrieving objects in React.js

Struggling to extract a country from an online JSON file that I am currently fetching. I am attempting to streamline the process by creating a function to retrieve the country from the dataset and avoid repeating code. However, I am encountering difficulti ...

JavaScript Thumbnail Slider Builder

I've been working hard on developing a custom JavaScript thumbnail slider that uses data-src. Everything seems to be in order, except the next and previous buttons are not functioning properly. Any assistance would be greatly appreciated. Here's ...

What is the best way to combine objects that share the same id?

View Image: Displaying Image POST ID's https://i.stack.imgur.com/JO5OF.png I attempted to resolve this using jQuery each, but I am uncertain about the next steps. Check out my Code: jQuery(document).ready(function($) { var data, exampleData, , ...