Assement requested for: Test your skills: Arrays 3;

Hi all,

I solved the third question on how to add the numbers to the arrays and it works fine.

for(let i = 0; i < myArray.length; i++) {
myArray[i] = myArray[i] + ’ (’ + i + ‘)’;
}

However, while checking here I found that the recommended solution is based on forEach().

Could you tell me if my approach is viable, as well, or if it comes with disadvantages. Same for the second line on how to add the numbers.

Thanks in advance,

Kai

1 Like

Hi Kia,

When I ran your code I had : ["1(0)", "2(1)", "3(2)"]

myArray[i] = myArray[i] + ’ (’ + i + ‘)’; calls the array index and then outputs the value into a ‘(0)…(1)…(2)’. which isnt what I think it should output if your asking for a sum of all the items in an array.

I have typed this up for you using the standard for loop:

let testArray = [1,2,3,4,5];

function addArray(array){
let total = 0; //Assigning an accumulator variable, this is where each call in the loop would store the sum before the next call.
for(let index = 0; index < array.length; index++){
//The Loop will iterate through the Array,
total += array[index]; //Here we are adding the value of the current index to the total,
};
return total; //This would return the total of the array;
}

Now here is the same thing using the Array.forEach() now the documentation on this is :ok_hand:

function addEach(array){
let sum = 0; //Setting an accumulator,
array.forEach((value)=>{
//This takes each value from the array and applies the following to it. It does so in an incrimental order going L-to-R in the array.
sum += value;
})
return sum //Returns the total
};

I highly recommend you read the documentation, there is a bit in there that says:

I hope that this helps bud.

=)

2 Likes

Thanks for the quick reply.
Though I am quite confused. It appears as if I might have gotten the task itself totally wrong (sorry no native). I was not aware that it is asking for a sum.

The task states that from a given array of names one should:
“Go over each item in the array and add its index number after the name inside parentheses, for example Ryu (0) .”

I figured an outcome like this was the goal. That’s why I created the loop to provide the index numbers and put them in parentheses behind each item. That’s why I thought my code provides the result that was asked for.

Could you help me here once more? I must be missing something.

Edit: I am getting your explanation on forEach() (thanks a lot), though I can’t figure out how to transfer it to the task at hand. It appears I don’t get what I am supposed to do in task.

For clarification the task was Array 3, task 3

Sorry for the confusion.

1 Like

Hey dont worry man, confusion is part of learning and trust me it gets even more confusing

I have to say, I didnt read the assesment, I just read that it was a sum, but hey, here is what I wrote up. Using the for loop,

//[1] Remove the last Item in the Array

myArray.pop();



//[2] Add new name to list (keeping inline with the Street fighter theme, what a game that first one was...ah nostalgia)

myArray.push('Eagle');

myArray.push('Gen');

// [3] Loop over the array. 

function printNames(array){

  let string =  ``;//String literals are really easy to build up

  for(let index = 0; index < array.length; index++){

    let name = array[index]//Need to store the name at each call

    string += `${name} (${index})`; // This then builds the string out

  }

  return string //This returns the string.

}

The Array.forEach() is a built in JS function(method) that lives in the Array object. Its been put in to cut down on the amount of for...loops that people have to write.

array.forEach() takes an array and goes through each entry in the arrya step by step. So you have and array [1 , 2, 3, 4] really this is [(0) : 1, (1) : 2, (2) : 3, (3) : 4 ]. the method goes in an ascending order. It doesnt care if the array is sorted or not. So it’s good practice to run an sorted array through it using the Array.sort().
The method breaks down the array into smaller array’s [(0) : 1] [(1) : 2]... At each call, it would apply any function we give it. Using an arrow function (anonymous function) we can give it the parameters, and it really only has two (index ,value)
so the method would look like this:

function printEachName(array){

  //This is is where the string will be stored

  let string = ``;

    array.forEach((index, name)=>{

      //Takes the index and the value of each  array item as it iterates through the array, 

      string += ` ${index} (${name}) `;//Building the string out

    })

    return string;//Returns the String

}

I hope that helps man =)

(my sleeping pattern has has been shattered since lockdown has been in effect)… :zombie:

1 Like

let myArray = [ “Ryu”, “Ken”, “Chun-Li”, “Cammy”, “Guile”, “Sakura”, “Sagat”, “Juri” ];

myArray.pop();
myArray.push(‘ali’);
myArray.push(‘johnny bravo’);

for (let i = 0; i < myArray.length; i++){
myArray[i] = ${myArray[i]} (${i});
}

let myString = myArray.join(’-’);
console.log(myArray);
console.log(myString);

1 Like

@therealalinares hey there, and welcome to our community. I’ve tested your code, and it works fine. Well done!

1 Like

thank you all for solving my doubts this quick!

1 Like

I find the documentation very useful. Thanks @drgaud