Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS array index number into value with string replace

Tags:

javascript

I have a multidimentional array:

(3) [Array(1), Array(1), Array(1)]
0:["('idDocDetail','0','$createdBy')"]
1:["('idDocDetail','2','$createdBy'),('idDocDetail','4','$createdBy')"]
2:["('idDocDetail','0','$createdBy')"]

I need to replace the string value idDocDetail with the index number, like this.

(3) [Array(1), Array(1), Array(1)]
0:["('0','0','$createdBy')"]
1:["('1','2','$createdBy'),('1','4','$createdBy')"]
2:["('2','0','$createdBy')"]

I'm trying to use replace, but I got the replace is not a function error.

array.forEach(function(item, index) {
  return item.toString().replace('idDocDetail', index);
    });

what am I doing wrong? Replace is the right way to do this?

like image 401
absolutkarlos Avatar asked Sep 25 '26 05:09

absolutkarlos


2 Answers

I do recommend you to learn to perform changes in immutable manner. This is where Array.prototype.map plays well

const data = [
  ["('idDocDetail','0','$createdBy')"],
  ["('idDocDetail','2','$createdBy'),('idDocDetail','4','$createdBy')"],
  ["('idDocDetail','0','$createdBy')"]
]

const modified = data.map((item, index) => 
   item.map(str => str.replace(/idDocDetail/g, index ))
)

modified.forEach(x => console.log(JSON.stringify(x)))
like image 66
Yury Tarabanko Avatar answered Sep 27 '26 19:09

Yury Tarabanko


Here, this works for your code structure. It uses map() to produce a new array by just replacing the string of interest with the index.

EDIT: Added a nested map for clarity + regular expression to find all instances of 'idDocDetail' in the string, not just the first one. replace method when given a raw string value only handles the first instance of a string occurring.

const array = [["('idDocDetail','0','$createdBy')"],
["('idDocDetail','2','$createdBy'),('idDocDetail','4','$createdBy')"],
["('idDocDetail','0','$createdBy')"]]

var find = 'idDocDetail';
var re = new RegExp(find, 'g');

let newArray = array.map((val, i) => val.map(string => {
  return string.replace(re, i)
}))

console.log(newArray)
like image 23
Christopher Messer Avatar answered Sep 27 '26 18:09

Christopher Messer