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)
2 Answers 2
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);
1 Comment
forEach; you are mutating the array as you are iterating over it which is not good practiceTo 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]);
.map()makes a lot more sense than.forEach().