Since we have 2018 already, another approach using Array.map and destructuring:
const groups = [
"apple0",
"banana0",
"pear0",
];
[].concat(...groups.map(item => [
item,
item.replace(0, 1),
item.replace(0, 2)
]
))
// result: ["apple0", "apple1", "apple2",
// "banana0", "banana1", "banana2",
// "pear0", "pear1", "pear2"]
Explanation:
groups.map(item => [item, item.replace(0, 1), item.replace(0, 2)])
takes each array item one by one (apple0
, then banana0
, …) and replaces it with an array of:
item
– the item itself (apple0
)
item.replace(0, 1)
– the item with zero replaced by 1
(apple1
)
item.replace(0, 2)
– the item with zero replaced by 2
(apple2
)
so the array looks like…
[
["apple0", "apple1", "apple2"],
["banana0", "banana1", "banana2"],
["pear0", "pear1", "pear2"],
]
…and then we need to flatten it, that's the [].concat(...
part. It basically takes array items (the three dots, read more about destructuring here), and merges them into an empty array.
If you want to replace any digit, not just zero, use regular expression:
"apple0".replace(/\d$/, 1)
// -> "apple1"
"apple9".replace(/\d$/, 1)
// -> "apple1"
\d
– any number character
$
- end of line
- the surrounding slashes tell JS that it's a regular expression, you could use
new RegExp("\d$")
instead, too