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']

Upvotes: 1

Views: 212

Answers (4)

Guerric P
Guerric P

Reputation: 31825

If you don't want to mutate the original arrays, then you have to rebuild new arrays like this:

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

const replace = (index) => (set) =>
  set.map((arr) =>
    Object.assign([], arr, { [index]: arr[index].replace(/-/g, "/") })
  );

const replaceThirdIndex = replace(3);

console.log(replaceThirdIndex(set1));

Upvotes: 0

Spectric
Spectric

Reputation: 31992

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)

Upvotes: 3

rexess
rexess

Reputation: 755

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)

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227280

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);

Upvotes: 1

Related Questions