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