vacadery
vacadery

Reputation: 9

loop through names array letter by letter

let names = ['pete', 'dave', 'sara', 'toni', 'michael'];
let name = "";
let names2 = [];


// names[i][j]



console.log (names);
console.log (names2); 

I have to find a way to loop through the names array letter by letter and have the output of names2 to be that same array buy processed letter by letter.

So far i have this:

for (let i = 0; i < names.length; i++) {
for (let j = 0; j < names[i].length; j++) {
    name += names[i][j];
    names2 += name;
    name = "";

console.log (names);
console.log (names2);

The output should be:

['pete', 'dave', 'sara', 'toni', 'michael']
['pete', 'dave', 'sara', 'toni', 'michael']

(this second one written down letter by letter and the first one is just the normal array that we set at the begining)

But what I'm getting is:

['pete', 'dave', 'sara', 'toni', 'michael']
petedavesaratonimichael

Can anyone help me?

let names = ['pete', 'dave', 'sara', 'toni', 'michael'];
let name = "";
let names2 = [];

for (let i = 0; i < names.length; i++) {
  for (let j = 0; j < names[i].length; j++) {
      name += names[i][j];
      names2 += name;
      name = "";
  }
}

console.log (names);
console.log (names2);

Upvotes: 0

Views: 95

Answers (3)

Mohammed Ashfaq
Mohammed Ashfaq

Reputation: 3426

let names = ['pete', 'dave', 'sara', 'toni', 'michael'];

const convertedNames= names.slice();

console.log(names);
console.log(convertedNames);

Upvotes: 0

GMachado
GMachado

Reputation: 801

When you do names2 += name; you are not adding name value to the array names2, instead it's converting the value to string and then concatenating.

To add to the array you should use the method push:

names2.push(name);

Upvotes: 0

FK82
FK82

Reputation: 5075

I'm unsure what this excercise is about, but here's a solution (without loops but with Array.map and Array.reduce).

let names = ['pete', 'dave', 'sara', 'toni', 'michael'];

const convert = (names) => names.map(name => Array.from(name).reduce((result, c) => `${result}${c}`, ''))

console.log(names);
console.log(convert(names));

In your solution, you are probably coercing your array to a string by using the overloaded += operator. You should be using Array.push or Array.concat instead when adding elements.

Upvotes: 2

Related Questions