0

I am stuck in a problem. I have user input of array which contains number as well as strings like:-

 3
apple
Lemmon
sugar
2
Ginger
Ice

This is the data that I am receiving. Now I have to manipulate the data as such that. "Whenever it encounters a number it creates a new array with exactly the number values in array".

Desired Output

Array1 ["apple", "Lemmon", "sugar"]
Array2 ["Ginger", "ice"]

Any Idea will help. Thanks in advance

Enigmatic
  • 602
  • 1
  • 8
  • 19
  • You can simply detect if the input is a number and create a new array. There are several ways to do this - https://stackoverflow.com/questions/175739/built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number – DannyMoshe Apr 30 '21 at 22:01
  • Like this array can extend and I want it should go in a new array everytime there is a number encountered. Can you please suggest one way to do it? – Enigmatic Apr 30 '21 at 22:18

1 Answers1

2

It depends on how you get the info. But this is the first idea I got to quickly solve your issue:

function makeArray(...info) {
  stringArray = [];
  i = -1;
  info.forEach(item => {
    console.log(item);
    if (Number(item)) {
      stringArray.push([]);
      i+=1;
    } else stringArray[i].push(item);
  });
  return stringArray;
}

makeArray(3, 'apple', 'Lemmon', 'sugar', 2, 'Ginger', 'Ice');

If you log that you get:

[ [ 'apple', 'Lemmon', 'sugar' ], [ 'Ginger', 'Ice' ] ]

It makes a 2D array. And from there maybe you can use it like that or just sepparate it easily.

Alfredo C.
  • 56
  • 2
  • nice solution! just a tip, it would be good to define your variables with `let` -> `let i = -1;` `let stringArray = [];` – buzatto Apr 30 '21 at 22:37
  • jaja, totally right! For doing it quickly I forgot that, and even left a console.log there. Thanks for pointing it out @buzatto – Alfredo C. Apr 30 '21 at 22:40
  • that's normal, it happens to all of us. you can always `edit` your answer to fix something or add more context. welcome to the forum! – buzatto Apr 30 '21 at 22:49
  • Great solution @AlfredoC... That was a great Help. – Enigmatic Apr 30 '21 at 22:59