Home > Software engineering >  Splitting array into multiple arrays
Splitting array into multiple arrays

Time:11-24

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.

CodePudding user response:

You can use .map() for each array:

const animals = ['dog', 'cat', 'lama']

const result = animals.map(animal => [animal]) 

console.log(result)
// [ ['dog'], ['cat'], ['lama'] ]

You can then push the results into another array or you can use .reduce() to generate the end result.

CodePudding user response:

You can use map here to take those individual values and return them to a new array as arrays, just by wrapping them in braces.

You can also define a splitter function and just call it against the array. This would be useful if you had to do it in a lot of places or if you had an array of these arrays and wanted to iterate over that and use the splitter constant on each, as in my last example where I use the splitter inside map.

let arr = ['cat', 'apple', 'frog'];
//console.log(arr);

let final = arr.map(m=>{return [m]});
console.log(final);

const splitter =(arr)=> arr.map(m=>{return [m]});
console.log(splitter(arr));

arr = arr = [
  ['dog'],
  ['dog', 'cat'],
  ['cat', 'apple', 'frog'],
  ['apple', 'dog']
];

final = arr.map(m=>{return splitter(m)});
console.log(final);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related