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

2
  • You can simply detect if the input is a number and create a new array. There are several ways to do this - stackoverflow.com/questions/175739/… Commented Apr 30, 2021 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? Commented Apr 30, 2021 at 22:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

nice solution! just a tip, it would be good to define your variables with let -> let i = -1; let stringArray = [];
jaja, totally right! For doing it quickly I forgot that, and even left a console.log there. Thanks for pointing it out @buzatto
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!
Great solution @AlfredoC... That was a great Help.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.