I have looked up answers on these questions How to split a long array into smaller arrays, with JavaScript and Split array into chunks but i still do not understand what i am doing wrong.
I have multiple random arrays that look like this
['dog']
['dog', 'cat']
['cat', 'apple', 'frog']
['apple', 'dog']
etc.
and i want to split them so they look like this
['dog']
['dog'] ['cat']
['cat'] ['apple'] ['frog']
['apple'] ['dog']
I was wondering if i could use a foreach loop to loop through all the arrays and split them into single arrays.
this is what my code looks like
var arrays = press.post_category;
arrays.forEach(function(item){
var arr = [];
var size = 1;
for (let i = 0; i < item.length; i += size)
arr.push(item.slice(i, i + size));
console.log(arr);
});
the output of this is
["d","o","g"]
["d","o","g"," ","c","a","t"]
etc.
which is not what i want. Im not sure why its splitting it into each individual letter instead of each value in the array.
I am trying to avoid SPLICE by all means and only use SLICE if necessary.
Thanks in advance.
EDIT: my output for the code is now. Ive tried to use flat() but that just brings it back to ["dog", "cat"].
var animals = [
[
[
"dog"
],
[
"cat"
]
]
];
I have the dog and cat that are in nested arrays and Im trying to get rid of the extra array so it would look like this instead
var animals = [
[
"dog"
],
[
"cat"
]
];