By Lloyd Nicholson


2019-01-11 12:03:29 8 Comments

I am creating a web-based accounting app for high school kids to use as practice. My transactionListArray contains all of my transactions that have been randomly generated behind the scenes in my JS code. The transactionListArray contains certain characters including the first character which is the date as an integer with a . following it (for example: 10. or 12. etc). After the date there is a sentence which creates the accounting transactions' wording, account names, payment methods and various other things.

A basic transaction produces this output:

27. Trusted Traders purchased trading stock to the value of R108756.

I have looked everywhere and I still cannot find the solution that suits my liking.

The problem I have been faced with for several days now, is trying to figure out how to use the regex match keyword to return a string. The issue comes in when I try match the currentString with the nextString which is the next value in the array.

See below:

let length = array.length-1;
for (let i = 0; i < length; i++) {
    let regex = /d+\./; // this returns the value of the first number(the date) and the "." symbol
    let currentString = array[i];
    let nextString = array[i+1];
    let currentDate = currentString.match(regex); // errors
    let nextDate = nextString.match(regex); // errors
};

This above doesn't produce the output I am expecting. The error as stated on currentDate and nextDate lines says:

TypeError: Cannot read property '0' of null

This issue is confusing because I have checked the current iteration and the next iterations values but it doesn't return my regex string.

I'm expecting this for example:

currentDate[0] = '11.';
nextDate[0] = '10.';

I then want to replace the nextString when the currentString and NextString are equal. Like this:

let replaceDateWithBlankSpace = (array) => {
    let length = array.length-1;
    for (let i = 0; i < length; i++) {
        let regex = /d+\./;
        let currentString = array[i];
        let nextString = array[i+1];
        let currentDate = currentString.match(regex); // TypeError: Cannot read property '0' of null
        let nextDate = nextString.match(regex); // TypeError: Cannot read property '0' of null
        if (currentDate[0] === nextDate[0]) { // checking if both are equal 
            nextString.replace(regex, "   "); // and then replacing the string regex that was calculated with blank space at array[i+1]
        }
    }
};

I call the function like this on my transactionListArray:

replaceDateWithBlankSpace(transactionListArray);

2 comments

@Ray Chan 2019-01-11 12:31:35

If you want to mutate the original array, you can do it like this:

const arr = [
    '25. Trusted Traders purchased trading stock to the value of R138756.',
    '26. Trusted Traders purchased trading stock to the value of R432756.',
    '26. Trusted Traders purchased trading stock to the value of R108756.',
    '28. Trusted Traders purchased trading stock to the value of R333756.',
];

const replaceDateWithBlankSpace = array => {
    const length = array.length - 1;
    const regex = /^\d+\./;

    for (let i = 0; i < length; i++) {
        const currentString = array[i];
        const nextString = array[i + 1];
        const currentDate = currentString.match(regex);
        const nextDate = nextString.match(regex);

        if (currentDate && nextDate && currentDate[0] === nextDate[0]) {
            array[i + 1] = array[i + 1].replace(regex, '   ');
        }
    }
};

replaceDateWithBlankSpace(arr);

console.log(arr);

@Lloyd Nicholson 2019-01-11 12:34:30

This works. Thanks.

@Lloyd Nicholson 2019-01-11 12:45:04

Can you explain this line please - if (currentDate && nextDate && currentDate[0] === nextDate[0])

@Lloyd Nicholson 2019-01-11 12:45:58

And why can’t I set nextString = nextString.replace(regex, ‘ ‘);

@Ray Chan 2019-01-11 12:47:50

For nextDate = nextDate.replace(regex, ‘ ‘);, because I declared the variable nextDate with the const key word, so error will be thrown when you set the value on nextDate again. If you want to set its value again, replace the const keyword with let

@Lloyd Nicholson 2019-01-11 12:49:09

thanks. That makes sense. Didn’t read that it was const

@Ray Chan 2019-01-11 12:51:19

For the line if (currentDate && nextDate && currentDate[0] === nextDate[0]), the first two conditions currentDate && nextDate is used to check whether there is a match from the string. Since .match will returns null if there is no match, and accessing null[0] will throw an error. The checking here is to ensure there is a match from the string before we execute the logic inside the block.

@Lloyd Nicholson 2019-01-11 12:52:34

okay thanks a lot

@Ray Chan 2019-01-11 12:53:10

Glad it helped :)

@dquijada 2019-01-11 12:31:35

Ok, I might have misunderstood you, so please check if this solution fits your needs:

// I define the transactions array that you generate randomly:
const transactionListArray = [
  '5. Lorem ipsum dolor sit amet',
  '5. consectetur adipiscing elit',
  '6. Praesent aliquet ut ex eget mattis',
  '7. Donec fermentum sodales quam',
  '7. quis vestibulum justo posuere quis',
  '8. Fusce tristique accumsan pretium',
  '9. Quisque ante metus',
  '9. vestibulum sed lacinia sed',
  '9. elementum ac nunc',
  '10. Suspendisse vel sollicitudin neque',
  '10. vel sagittis quam'
];

function replaceDateWithBlankSpace (array) {
  return array.map((transaction, index, array) => {
    const regex = /^(\d+\.)(.*)$/;
    
    let lastDate = array[index-1] ? array[index-1].replace(regex, '$1') : '';
    let thisDate = transaction.replace(regex, '$1');
    
    if (lastDate === thisDate) {
      return transaction.replace(regex, '$1').replace(/./g,' ')
               + transaction.replace(regex, '$2');
    } else {
      return transaction;
    }
  });
}

console.log(replaceDateWithBlankSpace(transactionListArray));

Related Questions

Sponsored Content

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5784253 View
  • 7214 Score
  • 79 Answer
  • Tags:   javascript arrays

30 Answered Questions

[SOLVED] How to append something to an array?

46 Answered Questions

83 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

3 Answered Questions

55 Answered Questions

[SOLVED] How to replace all occurrences of a string in JavaScript

39 Answered Questions

[SOLVED] Loop through an array in JavaScript

41 Answered Questions

[SOLVED] Sort array of objects by string property value

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

44 Answered Questions

[SOLVED] How to check if an object is an array?

Sponsored Content