3

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)

asked Oct 23, 2019 at 16:50
4
  • 2
    post the desired output as well Commented Oct 23, 2019 at 16:53
  • 3
    It's not clear exactly what you're attempting but it's probably true that .map() makes a lot more sense than .forEach(). Commented Oct 23, 2019 at 16:54
  • 1
    Anthony's answer with map seems to work with this. Commented Oct 23, 2019 at 16:56
  • 1
    You would use map for this, Anthony's answer with map works fine. Commented Oct 23, 2019 at 23:50

2 Answers 2

6

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);

answered Oct 23, 2019 at 16:53
Sign up to request clarification or add additional context in comments.

1 Comment

not with forEach; you are mutating the array as you are iterating over it which is not good practice
0

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]);
answered Oct 23, 2019 at 18:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.