Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
replace /g not working when used with map method

I have a set of arrays and I'm trying to change the dash on the dates to a slashes but the replace /g is not working when I use it in a map method.

let set1 = [['Jones', 'Ann', 'F', '6-3-1975', 'Red'],
['Perez', 'Maria', 'F', '4-2-1979', 'Green'],
['Samuels', 'Rika', 'M', '12-2-1973', 'Black']]

set1.map(arr => arr[3].replace(/-/g, "/"))
console.log(set1)

The result should be as shown bellow but the dashes are not changing

['Jones', 'Ann', 'F', '6/3/1975', 'Red'],
['Perez', 'Maria', 'F', '4/2/1979', 'Green'],
['Samuels', 'Rika', 'M', '12/2/1973', 'Black']
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Array.map does not mutate the original array. You have to assign the result after mapping back to set1.

You'll also have to assign the result after replacing back to the item at index 3 and return arr in the map function.

let set1 = [['Jones', 'Ann', 'F', '6-3-1975', 'Red'],
['Perez', 'Maria', 'F', '4-2-1979', 'Green'],
['Samuels', 'Rika', 'M', '12-2-1973', 'Black']]

set1 = set1.map(arr => (arr[3] = arr[3].replace(/-/g, "/"), arr))
console.log(set1)

If you don't want to create a new one, use Array.forEach:

let set1 = [['Jones', 'Ann', 'F', '6-3-1975', 'Red'],
['Perez', 'Maria', 'F', '4-2-1979', 'Green'],
['Samuels', 'Rika', 'M', '12-2-1973', 'Black']]

set1.forEach(arr => arr[3] = arr[3].replace(/-/g, "/"))
console.log(set1)

about 4 years ago · Juan Pablo Isaza Report

0

Another answer, but using forEach instead. This may use less memory compared to the map approach.

let set1 = [['Jones', 'Ann', 'F', '6-3-1975', 'Red'],
['Perez', 'Maria', 'F', '4-2-1979', 'Green'],
['Samuels', 'Rika', 'M', '12-2-1973', 'Black']]

set1.forEach(arr => arr[3] = arr[3].replace(/-/g, "/"))

console.log(set1)

about 4 years ago · Juan Pablo Isaza Report

0

The .map() function expects you to return the entire element you want to be in the resulting array. So, you need to return the entire arr value, not just the date string.

let set1 = [
  ['Jones', 'Ann', 'F', '6-3-1975', 'Red'],
  ['Perez', 'Maria', 'F', '4-2-1979', 'Green'],
  ['Samuels', 'Rika', 'M', '12-2-1973', 'Black']
];

set1 = set1.map(arr => {
  arr[3] = arr[3].replace(/-/g, "/");
  return arr;
});

console.log(set1);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!