Home > Software design >  Array of numbers to Array of one string
Array of numbers to Array of one string

Time:02-04

I need to [1, 2, 3] over to ['123']. I must return [1, 2, 3] over to ['123'] while using an arrow function (no regex):

Must be used:


const functionOne = (arrayOne) => {

};

console.log(functionOne([1, 2, 3]));

So, I tried the following:

First, I created a string. This gave me 1,2,3

Then, I removed the commas, so, I could join the numbers. This gave me 123.

Finally, I tried to put back the number as a string into the array but this didn't work. This gave me ['1', '2', '3'] instead of ['123']. I think the .split method is what is wrong in my code but I cannot find another one (currently learning JavaScript).

const functionOne = (arrayOne) => {

  let stepOne = arrayOne.toString(arrayOne => arrayOne.toString());

  console.log(stepOne);

  stepOne = stepOne.split(',').join('');

  console.log(stepOne);

  return stepOne.split('');

};

console.log(functionOne([1, 2, 3]));

CodePudding user response:

You can join using "" as the delimiter (it will automatically convert the elements to strings as it produces the output string), then put the result in an array as its only element ([____]):

const functionOne = (array) => [array.join("")];
console.log(functionOne([1, 2, 3]));

Issues with your original approach:

  • Array's toString completesly ignores the argument you're giving it, instead using its default behavior of join(",").
  • Splitting it on , again just gives you back an array, but this time of strings.
  • Rejoining that with join('') does give you "123", but doesn't put it in an array.

CodePudding user response:

const functionOne = (arrayOne) => {
  let stepOne = arrayOne.toString();
  stepOne = stepOne.split(',').join('');
  return [stepOne];
};

console.log(functionOne([1, 2, 3]));

The .toString() method will convert the array [1, 2, 3] to the string "1,2,3", then .split(',').join('') removes the commas and joins the numbers as a single string "123". Finally, return [stepOne]; returns the string "123" inside an array ['123'].

CodePudding user response:

You could take a recursive function.

const
    fn = ([v, ...rest]) => rest.length
        ? [v   fn(rest)]
        : [v];

console.log(fn([1, 2, 3]));

CodePudding user response:

Reduce is always an option when turning a list into something of a different shape.

const functionOne = (arrayOne) => {
  return arrayOne.reduce((result, item) => {
    result  = item.toString()
    return result;
  }, '');
};

console.log([functionOne([1,2,3])]);

Array.join is likely more optimized than this solution, but using reduce for this is a nice and tidy solution.

This has the added benefit that it just returns a string, then you can shove the result in an array if you like.

More info on reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

  • Related