user11910224
user11910224

Reputation:

How can i convert elements of an array in javascript into an independent array using forEach

I am trying to convert elements of an array to independent arrays and then adding these arrays to a new array. this is what i have tried. But cannot get it to work. splice method is not working properly with forEach,forEach just runs for half array and then exits.

what i expect is something like this [['Apple'],['Banana'],['Mango'],['Pomegranate']]

const fruits = ['Apple', 'Banana', 'Mango', 'Pomegranate']

function removeArrayItem(item,index){
    return fruits.splice(0,1)
}

const fruitsList = []

fruitsList.unshift(fruits.forEach(removeArrayItem))

console.log(fruitsList)

Upvotes: 3

Views: 126

Answers (2)

GauRang Omar
GauRang Omar

Reputation: 871


To convert

['Apple', 'Banana', 'Mango', 'Pomegranate']

to

[ ["Apple"], ["Banana"], ["Mango"], ["Pomegranate"] ]

you can try

    //using for each 
    const usingForEach = []; 
    fruits.forEach(el => usingForEach.push([el]));

    //using map
    const usingMap = fruits.map(el => [el]);

Upvotes: 0

Anthony
Anthony

Reputation: 6482

You can do it like this:

const fruits = ['Apple', 'Banana', 'Mango', 'Pomegranate']

console.log(fruits.map(fruit => [fruit]));

If you are set on forEach though, you can do it like:

const fruits = ['Apple', 'Banana', 'Mango', 'Pomegranate'];
const result = [];

fruits.forEach(fruit => result.push([fruit]));

console.log(result);

Something like this would work for splice:

const fruits = ['Apple', 'Banana', 'Mango', 'Pomegranate'];
const initialLength = fruits.length;
const result = [];

for(let i = 0; i < initialLength; i++) {
    result.push(fruits.splice(0,1));
}

console.log(result);

Upvotes: 6

Related Questions