0

I'm trying to get the values from an array so I can filter them. Using hints from Add single quotes in a string array javascript but it doesn't return the whole array with quotes around each value.

Tried:

var ages = Array.from({ length: 5 }, (_x, i) => i + 1);
console.log(ages); // [1,2,3,4,5]
ages = ages.toString(); 
console.log(ages); // "1,2,3,4,5"
const newArr = ages[0].split(",").map(x => x.trim());
console.log(newArr); // ["1"]

//desired: ["1","2","3","4","5",] or ["1","2","3","4","5"]

MBSteve
  • 19
  • 1
  • 4
  • 2
    `var ages = Array.from({ length: 5 }, (_x, i) => String(i + 1));` – Som Shekhar Mukherjee Jan 29 '23 at 13:37
  • 1
    This is an XY-Problem. That's your issue in filtering? – Roko C. Buljan Jan 29 '23 at 14:40
  • Thank you. Both answers work. I'm wanting to filter the Array.from (a longer array) [1,2,3...] to a new array of those number that end with (1),(2), etc. I couldn't seem to get it to work without converting ages to string numbers ['1','2', '3'...]. – MBSteve Jan 30 '23 at 10:40

1 Answers1

0

You are over-complicating this, particularly by first converting the entire array with toString(). It's as simple as follows:

const ages = Array.from({ length: 5 }, (_x, i) => i + 1);
const newArr = ages.map(age => age.toString());
console.log(newArr); // [ '1', '2', '3', '4', '5' ]
Dexygen
  • 12,287
  • 13
  • 80
  • 147