-1

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"
        ]
];
Sarah
  • 105
  • 1
  • 7
  • Hey, I wrote an answer, but now it's not 100% clear to me on rereading the question what the input data is. You don't have any quotes in those sample arrays, so technically [dog, cat] is an array of two variables, dog and cat. Do you mean ['dog', 'cat'], or do you mean ['dog, cat']. That is, do your arrays consist of a single comma separated string, or are they an array of strings that each contain one word? – Chris Strickland Nov 24 '21 at 00:06
  • Ive made an edit in the original post to exemplify better what im trying to fix. – Sarah Nov 24 '21 at 20:55
  • So would you like to get all the arrays in all the elements in one final array? Given the inputs you gave in the post, would you like to end up with `[['dog'], ['dog'], ['cat'], ['cat'], ['apple'], ['frog'], ['apple'], ['dog']]`? – Chris Strickland Nov 24 '21 at 22:06

3 Answers3

1

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.

Tsvetan Ganev
  • 8,246
  • 4
  • 26
  • 43
  • Is there a way so that the result is ['dog'], ['cat'], ['lama'] instead of [ ['dog'], ['cat'], ['lama'] ]. I dont want the arrays to be within arrays. – Sarah Nov 24 '21 at 15:33
  • If they are not within arrays, where will they be stored? – Tsvetan Ganev Nov 24 '21 at 21:03
1

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.

let arrays = ['cat', 'apple', 'frog'];
console.log(JSON.stringify(arrays));

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

You can also define a splitter function and just call it against the array.

let arrays= ['cat', 'apple', 'frog'];
const splitter=(arr)=>arr.map(m=>{return [m]});
console.log(JSON.stringify(splitter(arrays)));

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, like this:

let arrays = [
  ['dog'],
  ['dog', 'cat'],
  ['cat', 'apple', 'frog'],
  ['apple', 'dog']
];
const splitter=(arr)=>arr.map(m=>{return [m]});

let final = arrays.map(m=>{return splitter(m)});
console.log(final);

or if you needed to do this recursively with an array of unknown depth:

let arrays = [
  ['dog'],
  ['dog', 'cat'],
  [
    ['test', 'it', 'out'],
    ['cat', 'apple', 'frog']
  ],
  [
    ['one', 'more'],
    ['two', 'more']
  ],
  ['apple', 'dog']
];

const splitter=(arr)=>arr.map(m=>{
  return Array.isArray(m) ? splitter(m) : [m]
});

let final = splitter(arrays);
console.log(final);
Chris Strickland
  • 3,388
  • 1
  • 16
  • 18
  • I realized that the arrays become nested within one array, is there a way to avoidthat? and yes, i meant to do ['dog'] quotations around the strings. Sorry about that – Sarah Nov 24 '21 at 15:34
  • It's fine about the quotes, hat's what I thought you meant but I just wanted to make sure. Not sure I completely follow what you mean about the nesting, but I'm sure there is a way. – Chris Strickland Nov 24 '21 at 15:38
  • so right now the output of your code is final = [ [dog][cat] ] but i want final = [dog] [cat] instead – Sarah Nov 24 '21 at 17:46
  • what would [dog] [cat] be contained in? And there's no commas. Maybe it would be better if you used standard notation to write out your desired output. You can validate the json at https://jsonlint.com/. Then we'll be sure that we have a valid output design and there will be no confusion about the intent. – Chris Strickland Nov 24 '21 at 17:50
0

var arrays = [
      'dog',
      'dog,cat',
      'cat,apple,frog',
      'apple,dog'
  ];
  var arr = [];
  arrays.forEach((item) => arr.push(item.split(",")));
  console.log(arr);

Do you mean like this?

Hery Kurniawan
  • 344
  • 2
  • 8