-2

I want to change array with map() but it doesn't work.
Here is my code.

const colors = ["#9abc9c", "#9ecc71", "#9498db", "#9b59b6", "#967e22", "#974c3c", "#91c40f"];
colors.map(color => color[1]="1");

Input what i want is change every first number after "#" into 1.

colors = ["#1abc9c", "#1ecc71", "#1498db", "#1b59b6", "#167e22", "#174c3c", "#11c40f"];

I'd be so appreciate it if you let me solve this problem.

ivk
  • 1
  • 1
  • 1
    what are you trying to do here? What should be the expected result? – DecPK Oct 22 '22 at 12:40
  • 1
    `map` always returns a new array. Here it will return an array of `'1'` – DecPK Oct 22 '22 at 12:40
  • I suggest looking at [examples of using `map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#examples). – T.J. Crowder Oct 22 '22 at 12:41
  • Strings are immutable, so `color[1] = "1"` will do nothing. – Pointy Oct 22 '22 at 12:42
  • 1
    Also, strings are immutable, you can't change them by assigning to their letters. See: https://stackoverflow.com/questions/34874666/cant-assign-letter-by-index-is-it-implicit-conversion-error and https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript – T.J. Crowder Oct 22 '22 at 12:42
  • 1
    @Pointy - I already voted differently (because I'm silly), but you might want to VTC as https://stackoverflow.com/questions/34874666/cant-assign-letter-by-index-is-it-implicit-conversion-error or https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript – T.J. Crowder Oct 22 '22 at 12:43
  • Map doesn't change arrays, Map creates copies. Cease modifying arrays as simple as that one. Just create a new array with map, instead of modifying the existing array. – Mosia Thabo Oct 22 '22 at 12:44
  • my expected input is `["#1abc9c", "#1ecc71", "#1498db", "#1b59b6", "#167e22", "#174c3c", "#11c40f"]` – ivk Oct 22 '22 at 12:45
  • 1
    @T.J.Crowder it's always hard to vote when there are layers of competing errors :) – Pointy Oct 22 '22 at 12:49

1 Answers1

2

SOLUTION 1

If you want to replace first character after # with 1 then you can do as:

const colors = [
    '#9abc9c',
    '#9ecc71',
    '#9498db',
    '#9b59b6',
    '#967e22',
    '#974c3c',
    '#91c40f',
];
const result = colors.map((color) => color.replace(/\d/, '1'));
console.log(result);

SOULTION 2

You should always pick first solution but for another solution you can think below solution also.

const colors = [
    '#9abc9c',
    '#9ecc71',
    '#9498db',
    '#9b59b6',
    '#967e22',
    '#974c3c',
    '#91c40f',
];
const result = colors.map((color) => `#1${color.split('').slice(2).join('')}`);
console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42