skip to Main Content

Please I need an assistance, please how to loop through an array indexes and increment the output by 1
I mean like to loop through an array indexes and for the first output of the index 0 will logout the first alphabet, and for the index 1 will log out the second alphabet
For example an array like this one [mango, banana, apple, orange, pineapple] will produce an array like this [m, a, p, n, a] In javascript

I tried using for loop on the array and I’m just looping over the indexes not the indexes of the index

3

Answers


  1. Use Array.prototype.map(fn(element, index, array)):

    const data = ["mango", "banana", "apple", "orange", "pineapple"].map((string, i) => string[i])
    
    console.log(data)
    Login or Signup to reply.
  2. const myList = ["mango", "banana", "apple", "orange", "pineapple"];
    const myNewList = myList.map((fruit, index) => fruit.charAt(index));
    

    This will loop over your fruits, and create an array with the character at the index. However, this will break if the fruit’s length is less than the index it is at.

    Login or Signup to reply.
  3. You can use Array.from to create new array and pass a function that returns the character at the current index in the item.

    const fruits = ["mango", "banana", "apple", "orange", "pineapple"];
    
    const result = Array.from(fruits, (item, idx) => item[idx]);
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search